19

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?

Sun
  • 4,458
  • 14
  • 66
  • 108
  • Are you wanting to use the header text or the column/property name in the underlying data source? – David Jun 13 '12 at 09:44
  • You raise a good point which might stop me. The Header text can change depending on the grid data so I can't use that. However the column that I need to hide is a TemplateField which isn't bound to a datasource and it doesn't seem to have an ID. – Sun Jun 13 '12 at 09:53

3 Answers3

19

You can use the following code for it:

foreach (DataControlField col in gridReviews.Columns)
        {
            if (col.HeaderText == "Name")
            {
                col.Visible = false;
            }
        }
Imran Balouch
  • 2,170
  • 1
  • 18
  • 37
0

You can access the gridview by column name indirectly if you can access the data you used to bind the gridview and the gridview columns are in the same order as the datatable (and AutoGenerateColumns = false):

//Make ID column invisible by column name
gv.Columns[dt.Columns[ID].Ordinal].Visible = false;
Bolo
  • 1,494
  • 1
  • 19
  • 19
0

Not Tested for ASP.NET... Below line is For Windows Form solution ...

as this question is on top for windows form keyword also so posting this ..

my_gridview.Columns["ColumnName"].Visible = false;
Hietsh Kumar
  • 1,197
  • 9
  • 17