30 August 2007

Binding Complex Properties to GridView

Binding simple (int/string, etc) type properties to a TemplateColumn in a GridView is easy, but when you need to bind the Grid to an object that has properties that aren't simple types it gets a bit more complex.  The Bind method only works with simple types, so you need to use the Eval method and the dot operator to get the values from the complex type property [2].

[2]

<asp:TemplateField HeaderText="From Tag">

<ItemTemplate>

<asp:Label ID="FromTagTitle" runat="server" Text='<%# Eval("FromTag.Title") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

 

Filed under: ,
 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Ovidiu Petruescu said:

The easiest way to do this is to extend the BoundField and provide your own implementation for GetValue For Example:

public class EnhancedBoundField : BoundField

{

protected override object GetValue(Control controlContainer)

{

object component = null;

string dataField = this.DataField;

if (controlContainer == null)

{

throw new HttpException("DataControlField_NoContainer");

}

component = DataBinder.GetDataItem(controlContainer);

if ((component == null) && !base.DesignMode)

{

throw new HttpException("DataItem_Not_Found");

}

// use reflection to get the data from your child...

}

}

14 August 09 at 2:00 AM

Leave a Comment

Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker