Wednesday, May 12, 2010

Bind custom objects to gridview

You can bind list of flat structured objects only to gridview. I had a requirement where I wanted to bind list of composite object without using templates. I could not find any good article on Google. After putting some thought after how it is possible to achieve the same using templates, I could do it by making a custom class which inherited from Gridview bound field and I overrode its GetValue function as following.

Public Class CompositeBoundField
Inherits BoundField

Protected Overrides Function GetValue(ByVal controlContainer As Control) As Object
Dim item As Object = DataBinder.GetDataItem(controlContainer)
Return DataBinder.Eval(item, Me.DataField)
End Function


End Class

Now lets discuss how it can be used. Lets assume that my datasource object consist list of object of class "MyData" which is composed of objects from class "MyDataA", "MyDataB" as following

Class MyData
Public oA As new MyDataA
Public oB As new MyDataB
End Class

Class MyDataA
Public Property A as string 'please use the correct syntax of declaring property
End Class

Class MyDataB
Public Property B as Integer 'please use the correct syntax of declaring property
End Class

I must be binding datasource to my gridview something like as following
mygridview.datasource = ds 'ds is some prepoulated list of objects of MyData
mygridview.bind()

Before that you need to create your custom columns from your custom bound field class as following

Dim oColumn1 As New CompositeBoundField
oColumn1.DataField = "MyDataA.A"
Dim oColumn2 As New CompositeBoundField
oColumn2.DataField = "MyDataB.B"

(you can write a common function to achieve this or may use select statement)

What will happen now? After adding the column list to grid when it binds to its datasource, it uses reflection to populate its data for which grid will internally use GetValue method of bound field class. Because of our customboundfield class, it will now return you object of MyDataA.A and MyDataB.B which grid can lookup in datasource and get the data.

The good part of this approach is that your object could be nested at any level and you can still bind it with grid.

No comments:

Post a Comment