Binding Listbox to bindinglist, filter on item property

我的未来我决定 提交于 2019-12-13 04:27:41

问题


I'm working on a Winforms application and I have a bindinglist of objects that I want to bind to a listbox. I got this to work, but what I want to do next, is only display items where a particular property is true.

So I have a class with a bindinglist

class DataBuilder
{    
    public BindingList<TableSet> allTableSets = new BindingList<TableSet>();
}

And a class TableSet with some properties

class TableSet
{
    public string TableSetName {get; set;}
    public bool IsPopulated {get; set;}
}

And now on my form, I want to bind a listbox to the allTableSets, but only show the items where IsPopulated == true

What I have so far on my form just shows all the items in the allTableSets list

public partial class MainForm : Form
{
    DataBuilder dataBuilder = new DataBuilder();
    {
        this.populatedTableSetsListBox.DataSource = dataBuilder.allTableSets;
        this.populatedTableSetsListBox.DisplayMember = "TableSetName";
    }
}

I've been looking around the web but haven't found anything that seems similar to what I"m trying to do. Any suggestions or alternate methods are greatly appreciated. Thank you


回答1:


Try this: in your DataBuilder class, have a function that returns a subset of your items based on your filter condition.

For example, in your DataBuilder class:

    public BindingList<TableSet> someTableSets()
    {
        BindingList<TableSet> someTableList = new BindingList<TableSet>();
        foreach (TableSet TS in allTableSets)
            if (TS.IsPopulated == true)
                someTableList.Add(TS);
        return someTableList;
    }

Then, in your MainForm, instead of setting the DataSource to allTableSets, set it equal to the result of the someTableSets() function:

    this.populatedTableSetsListBox.DataSource = dataBuilder.someTableSets();


来源:https://stackoverflow.com/questions/14820122/binding-listbox-to-bindinglist-filter-on-item-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!