简体   繁体   中英

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#. 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.

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. 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. 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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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