Friday, 6 December 2013

Customize headers for the ASP.Net Gridview control dynamically

I almost exclusively bind the data for my gridview in the code behind as often the same gridview is used for displaying different tables. It also gives the user more control to make minor changes in the database tables without having to redesign the UI every time. So a lot of things happen in the gridview's onRowDatabound event which is the event that gets triggered when the data is being bound to the elements of the gridview. For instance this is where you can change the background colour of cells depending on their value and add formatting to the text in the cells etc but as I'm going to show you below you can also add and format the header rows dynamically depending on the data.

In this particular gridview I am adding three extra rows as headers as well as formatting the data rows depending on if they are in edit mode or not


The method that created as add the new header rows this is shown below:


If you are just displaying data you can finish here. However one thing to bear in mind is that if you are calling the commands on individual rows such as edit/update etc you are going to have a slight problem as there is a mismatch of the index sent to the code behind (which has three extra rows!) compared to the actual index of the row you want to update as the page doesn't know about the extra rows you have added dynamically when you are of reloading the page. So in the RowEditing event you simply subtract the extra rows from the e.NewEditIndex. This seems to work a little different depending if you have autogenerated the edit/update buttons or if you have added them in a template field. For this particular case I have added them in a template field.

No comments:

Post a Comment