简体   繁体   English

在C#中将列动态添加到Gridview-if语句过多

[英]Dynamically add columns to a gridview in C# - Too many if statements

I am working to clean up some code, and what I am working with is a gridview that is being created in the code-behind in C#. 我正在清理一些代码,并且正在使用的是在C#的代码隐藏中创建的gridview。 The boundfields that were created have a visible property that that will later determine if it is added to the collection of columns that the gridView will contain. 创建的边界域具有可见属性,该属性稍后将确定是否将其添加到gridView将包含的列的集合中。

When the gridView is built, it references a property that represents the default column collection, but within this property, each boundfield's visible property is evaluated with an if statement, where if it's visible, it's added to the collection. 构建gridView时,它引用一个表示默认列集合的属性,但是在该属性内,每个边界域的visible属性都使用if语句进行评估,如果可见,则将其添加到集合中。 The code looks like this: 代码如下:

private GridView.BaseFieldCollection _defaultColumns;

private GridView.BaseFieldCollection DefaultColumns
{
    get
    {
        if (Col1.Visible)
        {
            _defaultColumns.Add(Col1);
        }
        if (Col2.Visible)
        {
            _defaultColumns.Add(Col2);
        }
        if (Col3.Visible)
        {
            _defaultColumns.Add(Col3);
        }
        if (Col4.Visible)
        {
            _defaultColumns.Add(Col4);
        }
        if (Col5.Visible)
        {
            _defaultColumns.Add(Col5);
        }
    }
}

The problem is that there are 30 or so fields to be evaluated, and having 30 or so if statements doesn't sit well with me. 问题是要评估的字段大约有30个,如果语句不适合我,则有30个左右。 I was hoping that there might be a more elegant solution to this. 我希望可以对此有一个更优雅的解决方案。 The though crossed my mind to add all of the columns to some sort of collection object (list, array, etc.) and then looping through that, but it seemed that doing so might be less efficient. 尽管我想到了将所有列添加到某种收集对象(列表,数组等)中,然后循环遍历,但似乎这样做的效率可能较低。

Any thoughts on how to do something like this a bit more elegantly? 关于如何更优雅地执行此类操作的任何想法? I'm stumped... 我难过...

Thanks 谢谢

but it seemed that doing so might be less efficient 但似乎这样做的效率可能较低

This is irrelevant until this code becomes the bottleneck. 在此代码成为瓶颈之前,这​​是无关紧要的。 Throw in a bit of, for example, database access and this bit of code will never be the bottleneck. 例如,进行一些数据库访问,而这部分代码将永远不会成为瓶颈。

var cols = new[] {Col1,Col2,Col3}; // etc
foreach(var col in cols)
{
  if(col.IsVisible)
    _defaultColumns.Add(col);
}

or perhaps: 也许:

var cols = new[] {Col1,Col2,Col3}; // etc
_defaultColumns.AddRange(cols.Where(c => c.IsVisible));

您可以使用转换器显示(或不显示)具有可见性属性的绑定列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM