TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Binding a GridView to an Object Graph

Today I received an email regarding one of my previous posts:

re: ObjectDataSource, GridView, and DataKeyNames

Now, if my Person class has a property Country which returns a Country object (with properties CountryId and CountryName). How would you bind a gridview to display the list of persons (with Id, Name, Age and CountryName). The only way I could get this to work is to have the CountryName as a property on the Person class, which becomes unacceptable for more complex classes. Any ideas?

The answer is: create a template field and use Eval(). I have been able to bind to a graph of objects like this without any problems.

<asp:TemplateField HeaderText="CountryName">
   
<ItemTemplate>
      
<%# Eval("Country.CountryName") %>
    
</ItemTemplate>
</
asp:TemplateField>

Hope that helps.


Digg!

posted on Thursday, December 22, 2005 8:20 AM

Feedback

# re: Binding a GridView to an Object Graph 12/22/2005 9:53 AM midwest

Merry Christmas to you too!!!

Thanks for the quick response, but I get the 'expression expected' error when I use the above code.

# re: Binding a GridView to an Object Graph 12/22/2005 9:57 AM Sean Chase

Hmmm. Can you post roughly what your class looks like?

# re: Binding a GridView to an Object Graph 12/22/2005 10:05 AM midwest

my mistake. got it to working now.

I just have to read up more on when to use Eval and when to use Bind. Any ideas on that?

Thanks!!!

# re: Binding a GridView to an Object Graph 12/22/2005 11:18 AM Sean Chase

Sure, check out...

http://www.15seconds.com/issue/040630.htm