问题
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