<ObjectDataSource /> and dynamic template columns

Today I came across an issue when i tried to add template columns to GridView dynamically. The gridview was bound to Object Data Source and was set with paging.

I needed to add the columns dynamically, according to the selected date range. for this, i needed to get the event where i could fetch the datatable returned from ODS and add columns to gridview accordingly. I cant use autogeneratecolumns feature due to some reasons.

Initially when i was adding the columns to gridview in ODS.Selected event. It was resulting in the gridview was being bound to data source and data was being fetched again again resulting in stack over flow exception.

I then used the following trick to solve this problem

Dim dtselect As DataTable

Protected Sub ObjectDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs) Handles ObjectDataSource1.SelectedIf TypeOf e.ReturnValue Is DataTable Then

dtselect = e.ReturnValue

End If

End SubThen ,  on preRenderComplete event of the page, I added the columns dynamically Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete

‘generate dynamic columns

Dim dt As DataTable = Me.dtselect

Dim index As Integer = dt.Columns.IndexOf(“Date1”)

Dim tc As TemplateField

Dim Dates As String() = Me._Dates.Split(“,”c)

Dim i As Integer

If index >= 0 Then

For index1 As Integer = index To dt.Columns.Count – 1

tc = New TemplateField()

tc.ItemTemplate = New AttendanceTemplatedColumn(“Date” + index1.ToString, DataControlRowType.DataRow, Dates(i))

tc.HeaderTemplate = New AttendanceTemplatedColumn(“Date” + index1.ToString, DataControlRowType.Header, Dates(i))


tc.ControlStyle.Width = Unit.Pixel(“130”)

i += 1


End If

End Sub


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: