Hide a GridView column by name at runtime in ASP.Net

Sun picture Sun · Jun 13, 2012 · Viewed 33.9k times · Source

Is it possible to show/hide a GridView column at runtime by name?

I can do it via the index like the following:

gridReviews.Columns[4].Visible = false;

However I'd like to do the following:

gridReviews.Columns["Name"].Visible = false;

What's the best way to do this?

Answer

Imran Balouch picture Imran Balouch · Jun 13, 2012

You can use the following code for it:

foreach (DataControlField col in gridReviews.Columns)
        {
            if (col.HeaderText == "Name")
            {
                col.Visible = false;
            }
        }