Thursday, May 26, 2011

Programmatically Setting Header on ASP.NET GridView

It is actually very frustrating to change the header text on an ASP.NET GridView if you don’t do it in the right place. At first, I thought I would do it in the PreRender event as I figured that was plenty late in the cycle and should stick. Then I noticed it would not stick when I would sort for example.

In the end, it was very easy once I figured out what the proper event in the page lifecycle to use. You answer to this riddle is the RowCreated event. My GridView is called GridView1 in this example. I added onrowcreated=”GridView1_RowCreated” to my GridView in my .aspx file. In my code behind this is the code I used.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header && e.Row.Cells.Count > SOME_COLUMN_INDEX)
    {
        e.Row.Cells[SOME_COLUMN_INDEX].Text = "New Header Text here";
    }
}

Some things to know. You can’t reference the HeaderRow because it is still null at this point. It is there, but not accessible via the GridView1.HeaderRow property. You need to use e.Row instead. You can be guaranteed that this is not null since we are its event handler. You may also want to make sure the cell you are trying to set is not out of bounds. As long as you check to make sure you are in the header row you should be ok though. An example of when you would not have cells is when you get the EmptyData row which is displayed only when there are no rows to display. In that case, there are no headers. So, in general, I found it safe to always check to make sure the item I assume is in the array is actually in the array.

1 comment:

SM said...

Hi,

I've tried using the RowCreated event and discovered that the best place to attach the event handler is through the ASPX page markup. If you assign the event handler programmatically, you need to be sure that the code block you assign it in gets called in all scenarios e.g. sorting, pagination etc.