<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


<ObjectDataSource runat=”server” EnablePaging=”true” ID=”ODS2″ />

February 16, 2007

Here i am with another post about object data source (ODS). This time i will discuss some small tidbits when using ODS with GridView,instead of paging and filtering data using ODS.


 First I am going to discuss the deletion of record in Gridview , when it is used with ODS. Typically we use RowCommandEvent and check the commandName property of ‘e’ parameter , to perform the functionality e.g

Protected Sub gvwDiaryEntries_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvwDiaryEntries.RowCommand

Select Case e.CommandName

case “DeleteCmd”

‘do some thing

end select
end sub

But the things change a little bit when GridView is used with ObjectDataSource. In that case, RowCommandEvent is not fired instead ODS Deleting Event is fired.

Protected Sub ODSContacts_Deleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs) Handles ODSContacts.Deleting

Dim AddressID As Long = e.InputParameters(0)


e.InputParameters.Add(“AddressID”, AddressID)

End Sub

The ODS adds the DataKeyValue of specified row in the InputParameters collection, passed to this event Handler in parameter named ‘e’. But it doesnt give any proper name to it.

So, we need to clear the parameters collection and re-add it. Before that, we have to save the value of the DataKeyValue in arbitrary variable.

The parameter name “AddressID” is the parameter of the Delete Method.The delete method nameis  specified in DeleteMethodName property of ODS. Dont forget to set the DataKeyNames property ot GridView.


Second thing I am going to discuss, is passing of parameters to data source when we are implementing paging in our class.

For example

class mydataclass

public function GetData(ID as integer,ParentID as integer,StartRowIndex as integer,MaxRows as integer)as dataset

‘returns the PAGED data

end function

public function GetDataCount(ID as integer) as dataset

‘returns the count of the TOTAL data

end function

end class

If we bind our class to ODS and enable the paging at ODS, we need not to pass paging parameters (StartRowIndex and MaxRows ) to GetDataCount() method.

To implement this we need to handle the Selecting event of ODS as follows:

Protected Sub ODSContacts_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) Handles ODSContacts.Selecting


If e.ExecutingSelectCount = False Then

‘pass these paramters only when count is not being fetched. These parameters will be passed to GetData() method

e.InputParameters.Add(“ParentID”, 1)

End If

‘pass the other paramters . this parameter is common to both GetDAta() and GEtDataCount() methods

e.InputParameters.Add(“ID”, MyBase.UserID)

End Sub

ExecutingSelectCount property returns true when Count of the data  is being fetched. So, we have only passed paging parameters to ODS if data count is not being fetched. (Remeber, when we use paging at ODS, it take two trips to the server. Refer to my previous post for the details)

So , what happens when selecting event is raised that it checks if the data is being fetched, it passed Id,ParentId and paging parameters (paging parameters are passed automatically) to GetData method.

 Next time , when count is being fetched, it automatically igrnore those paging parameters and pass only those parameters which are explicitly defined e.g. ID in this case.

I hope this article to be very helpfull to all of you. Feel free to contact me if you have any questions.

<ObjectDataSource runat=”server” EnablePaging=”true” />

April 30, 2006

Here I am , with my first post. I have explored some features of ObjectDataSource control with GridView, which is shipped with ASP.net 2.0. The ObjectDataSource control is used to bind the controls to middle-tier busines objects. I have demonstrated some of the features of ObjectDataSource control with the help of an example, for which I could have easily used XMLDataSource control. I did this because, when you download some thing from internet saying connect to database. This database connectivity always causes some problems, with some of you. So, for the purpose of keeping the things easier for you, I have used ObjectDataSource(it will be called 'ODS' for the rest of the article)  control with XMLFile.


There are two ways , through  which  we can implement the paging functionality into our application.

  1. Use the paging behaviour of the control (e.g. GridView)
  2. User the paging at Datasource level.

The first approach leads to the fact that the control loads all the data from data source , then displays selected records based on current page number and page size of the control. This means that a lot of data has to be travelled across the network, which may be decrease the efficiency of the application. To implement this functionality, we just need to set EnablePaging and PageSize properties on the GridView To limit the amount of data which is going to be travelling on the network, ASP.net 2.0 supports the paging at DataSource level i.e. we will be sending only the data which is required to be displayed at the control. The beauty of ASP.net 2.0 is that you can write "Zero Code" websites, with very very little modification to business objects. Most of the magic is done behind the scenes , by .net framework 2.0. You dont need to write that much code for it, once you understand this magic. All of the stuff can be done by just setting the appropriate properties of data source controls. To enable paging at datasource level, you need to set EnablePaging property of ODS. There are some properties which need to be shed some light on.

  1. TypeName
  2. SelectMethodName
  3. SelectCountMethod
  4. StartRowIndexParameterName
  5. MaximumRowsParameterName


This property represents the fully qualified name of the business object , which is going to return us the data we will be displaying in the control. Its a class name of the middle-tier object. If you consider , default.aspx : The ProductsList class in the App_Code folder is the one, which we willl be using to get data.


This property represents the name of the method of the business object , which is going to return us the data we will be displaying in the control. If you consider , default.aspx : The GetProducts() method of ProductsList class in the App_Code folder is the one, which we willl be using to get data.


This property represents the name of the method of the business object , which is going to return us Count of the total numbers of rows of the data, we will be displaying in the control. If you consider , default.aspx : The GetRowCount() method of ProductsList class in the App_Code folder is the one, which we willl be using to get Count of the data rows.


This property represents the name of the parameter, which represents the first row of the subset of data, we are going to display on the page.


This property represents the name of the parameter, which represents the maximum rows, we are going to display on the page.  There is also a property named "SelectParameters", which represents the paramters which we are going to pass to the method ,which is specified in "SelectMethodName" property of ODS. These parameter values can be obtained from any thing ranging from form control value to cookie value.

Parameter Passing

How the parameters to the select method will be passed? If  EnablePaging property of ODS is set , then the parameters specified in the property of ObjectDataSource.StartRowIndexParameterName and ObjectDataSource.MaximumRowsParameterName are passed to the select method and in the same order.Therefore, the signature of your SelectMethod must contain these two paramter names.e.g ProductsList.GetProducts(int StartRow,int PageSize)  If you want to pass any other parameter in Select Method, add it in SelectParameters property of ODS. This parameter will be passed before the two parameters , which are mentioned above. You can see the signatures of ProductsList.GetProducts() method which contains two parameters , whose names are specified in ODS.StartRowIndexParameterName and ODS.MaximumRowsParameterName properties. Now, if you want any additional paramter to be passed, which are needed for your own business logic, add it in ODS.SelectParamters property and modify the signature of ProductsList.GetProducts() as follows: DataTable GetProducts(MyNewParameter,StartRow,PageSize) MyNewParameter is that parameter which is added in ODS.SelectParameters property. Another interesting fact is that you dont need to pass values for StartRow and PageSize  parameters manually. The .net framework automatically pass the values in these paramters such that StartRow parameter will contain starting row index for the current page and PageSize will be passed the value of GridView.PageSize property. (Note: It is not necessary to name the second paramter as PageSize. It can be any other parameter name and yet the value will be passed by .net framework correctly). Since, we are returning only those rows which are to be displayed on the current page, how will the gridview know the total number of rows in the data source? The answer is using the method which is specified in ODS.SelectCountMethod property. This method takes no parameters and returns integer. This method should return the total number of rows in the data source so that GridView could set its pager appropriately. For example, if there are 20 rows in the table and PageSize of GridView is set to 10 and method named specified in ODs.SelectCountMethod returns 10 , then GridView wont show the paging indicators, since it will only see 10 rows which are equal to its PageSize.

ObjectDataSource Events

ODS has two events which are important in this context. The ODS has Selecting Event which is fired before it fetches data from Business object and ODS.Selected event is fired when data has been fetched. The selecting event is fired two times every time when data is retrieved. One for data fetching and for getting row count. You can check this by checking the e.ExecutingSelectCount property. It returns true if row count is being retrieved else false. So, for every data fetch, there are actually two trips to business object, one for fetching data and  the next is for getting row count . One time the SelectMethod will be executed  and other time the SelectRowCountMethod, respectively.


GridView automatically sorts the data for you. There is no need to take any special steps for it. Just Set the AllowSorting property of GridView to true. ODS has event named Sorting , which is fired before the sorting takes place. Below are the steps you need to perform to setup your page for paging and sorting using ODS and GridView.

  1. Add GridView
  2. Add ODS
  3. Add Class which represents the business object.
  4. Set ODs.TypeName to Class name which represents the Business object.
  5. Set ODS.SelectMethod name to name of the method which return data
  6. Set ODS.SelectCountMethod to name of the method which return row count
  7. Set ODS.StartRowIndexParameterName  and ODS.MaximumRowsParameterName
  8. Modify the signature of your select method to include above two parameters.
  9. Implement the SelectMethod and SelectCountMethod
  10. Set the GridView.DataSourceID to Id of ODS.
  11. Run the page in browser

Unfortunately, wordpress doesnot allow the upload to zip files. So , if you need the code, leave a comment. 

I will be coming up with more on ODS and GridView next time. So, stay sharp ….