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

2020-08-09 07:22发布

问题:

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?

回答1:

You can use the following code for it:

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


回答2:

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;