Change ASP.NET GridView Header Text at Runtime

Continuing my ASP.NET GridView Tips and Tricks series, this post shows how to change the ASP.NET GridView Header Text at runtime.

I have seen many users using the RowCreated event, but I prefer the RowDataBound as it gives me more control, especially in cases where you need to change the values of Data bound controls.

Here’s the code to change the GridView HeaderText at Runtime. Let us first see how the GridView is declared

gridview-header-text

Now write the following code in the RowDataBound event to change the HeaderText of the 3rd column. Note that column index starts from zero.

protected void GridVie1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check for a condition
if (1 == 1)
{
GridView1.Columns[2].HeaderText = "Price(10 Units)";
}
}

gridview-header-text-change




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Unknown said...

Is a really nice idea what you are dping!!! Thanks!
I tried your code to change the header text of my gridview on server side, after asigning datasourse and databind the model.... but Im getting an "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" error :/ any idea of what Im doing wrong?

Suprotim Agarwal said...

Are you using DataKeys anywhere. What does GridView.DataKeys.Count result to?

Abhisar said...

I am also getting the same error....

"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

Unknown said...

>In window application. how to change the header text?