C# 在 ASP.Net 中在运行时按名称隐藏 GridView 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11012059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:06:33  来源:igfitidea点击:

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

c#gridviewhideasp.net-4.0

提问by Sun

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

是否可以在运行时按名称显示/隐藏 GridView 列?

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?

做到这一点的最佳方法是什么?

回答by Imran Balouch

You can use the following code for it:

您可以使用以下代码:

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

回答by Bolo

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):

如果您可以访问用于绑定 gridview 的数据,并且 gridview 列与数据表的顺序相同(并且 AutoGenerateColumns = false),则您可以通过列名间接访问 gridview:

//Make ID column invisible by column name
gv.Columns[dt.Columns[ID].Ordinal].Visible = false;