Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to Object Itself, Not One of It's Properties

Using Asp.net's Bind() method, how do I bind to the object itself, not one of it's properties?

like image 494
Ryan Avatar asked Sep 15 '09 16:09

Ryan


4 Answers

I think what Ryan means here like if you have to an object like this

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And if you bind Person object to anywhere in GridView or Repeater to any DataSource you only bind Person and it get a default bind value from one of its properties. support we have a variable Ryan from Person type so i want to get the variable value from calling <%# Eval("Ryan") %> not <%# Eval("Ryan.FirstName") %>

I tried to put an attribute DefaultBindingProperty for the class but it's not working

[System.ComponentModel.DefaultBindingProperty("FirstName")]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

So does any one knows how to do it properly?

like image 114
Ahmed Magdy Avatar answered Nov 09 '22 14:11

Ahmed Magdy


I ended up working around this by adding a property called SelfReference that simply returns this. If anyone reads this and has a better solution, I'd like to hear it.

like image 40
Ryan Avatar answered Nov 09 '22 14:11

Ryan


You may use Container.DataItem instead: Item='<%# Container.DataItem %>'

like image 2
Mehdi Avatar answered Nov 09 '22 13:11

Mehdi


I'm not sure to what exactly you want to bind. The only thing that would make sense to me at the moment is to bind to some UI control, say a DropDown control for instance.

There usually some text properties for the value being displayed and value properties for the actual value to function as identifier. On the Dropdown

  • DataTextField
  • DataValueField

There you specify DataTextField = "Firstname" and DataValueField = "Id" given that you have an object that has properties "Firstname" and "Id".

On lists you can use the Eval function directly on your ASPX code or you add server-side controls (i.e. Literals, Labels) inside the list templates and implement the ItemDataBound event (taking the Repeater as example). Here's a good example which illustrates this further.

Hope I was able to help a little ;)

like image 1
Juri Avatar answered Nov 09 '22 15:11

Juri