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


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)";


Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


Judith M Carbonell Alfonso 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?