Home > OS >  WF .Net ComboBox Control - How to show only items that match a condition
WF .Net ComboBox Control - How to show only items that match a condition

Time:10-23

I have a BindingList list and a ComboBox dropdownUI.

If I do: dropdownUI.DataSource = list, all the employees in the list will show in the drop down. I want to know if there is a way to only show the employees that have hidden = false so when I modify the employee hidden attribute, I can hide the record from the combo box?

public class Employee {
   public string name {get; set;}
   public bool hidden {get; set;}
   public Employee(string name, bool hidden) {
      this.name = name;
      this.hidden = hidden;
   }
}

CodePudding user response:

There is no way using the BindingList itself. It implements the IBindingList interface but you need the IBindingListView interface to get filtering. You have three main options:

  1. Define your own custom class that implements IBindingListView.
  2. Populate a DataTable with the data and either bind that directly or bind it via a BindingSource. When you bind a DataTable, the data actually comes from its DefaultView, which is type DataView. Both DataView and BindingSource implement IBindingListView.
  3. Create a new list based on the desired filter and bind that instead of the original list.

The first two options would allow you to modify an item and have the filter automatically update the UI, while the third option would require you to generate a new filtered list every time you modify an item.

  • Related