Pages

Wednesday, May 12, 2010

Using a Child Object's Property in a GridView Bound to an Object Data Source

The Object Data Source control is a nice way in ASP.NET webforms to bind a GridView control to a business object. It helps organize the method calls and events associated with the object and does save a lot of coding that must otherwise be done manually. Another benefit of binding a GridView to an ODS is that it will automatically create all of the bound columns in your GridView based on the properties on the object. So in the class below, FirstName, LastName, and Address will be displayed in the GridView.

Public Class Customer

Private mFirstName As String = String.Empty
Private mLastName As String = String.Empty
Private mAddress As String = String.Empty
Private mCustomerOrder As Order = Nothing

Public Sub New()
'Default class Constructor
End Sub

Public Property FirstName() As String
Get
Return mFirstName
End Get
Set(ByVal value As String)
mFirstName = value
End Set
End Property

Public Property LastName() As String
Get
Return mLastName
End Get
Set(ByVal value As String)
mLastName = value
End Set
End Property

Public Property Address() As String
Get
Return mAddress
End Get
Set(ByVal value As String)
mAddress = value
End Set
End Property

Public Property CustomerOrder() As Order
Get
Return mCustomerOrder
End Get
Set(ByVal value As Order)
mCustomerOrder = value
End Set
End Property

End Class
However notice the class property above named 'CustomerOrder' which is of type 'Order' and is an object instance property on the Customer Object. The 'Order' class contains a property named 'ItemName' that you would like to also have bound to your GridView. By default the ODS control will not map these properties on the child object for you. So how do we access this child object's properties and use it as well? Well with a little help from the forums, we find that you can add a 'TemplateField' column to your GridView, and access the field through data-binding expressions with a [ChildObject.PropertyName] syntax. Let's take a look below how this can be accomplished:







Using the Data-Binding 'Eval()' expression we are able to have a one-way read only binding of the 'ItemName' property. If you needed an updateable column you could use the 'Bind()' expression. The Eval method evaluates late-bound data expressions in the templates of the GridView control. If you need more information about the Eval() and Bind() data-binding expressions in VB.NET, take a look to the following MSDN link:

Data-Binding Expressions Overview

One last point to mention is concerning the ODS control. This post syntactically and programmatically is the same for those of you that manually bind a GridView control and do not use an ODS. The main elements here were the type of column used 'TemplateField' and the Data-Binding expressions 'Eval()' to access the child object's properties.

0 comments:

Post a Comment