blog Move

March 24, 2007

dthis  blog has now been moved at


<ObjectDataSource /> and dynamic template columns

March 13, 2007

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