Need some help with adding filter to my ComboBox drop down list(windows Forms Visual studio 2015)
The drop down is populated as per below:
In case you are using a Dictionary as data source, the following can be useful. I created a static function in the form to be able to reuse it as I have several ComboBox instances for which I wanted to have the same behavior. Simply call the function from the TextUpdate event passing the control name and the source dictionary.
private static void FilterComboBox(ComboBox combo, Dictionary dataSource)
{
var filter = combo.Text;
if (string.IsNullOrWhiteSpace(filter))
return;
var filteredItems = dataSource.Where(kv => kv.Value.Contains(filter)).ToDictionary(k => k.Key, k => k.Value);
combo.DisplayMember = "Value";
combo.ValueMember = "Key";
combo.DataSource = new BindingSource(filteredItems, null);
// this will ensure that the drop down is as long as the list
combo.IntegralHeight = false;
combo.IntegralHeight = true;
combo.DroppedDown = true;
// remove automatically selected first item
combo.SelectedIndex = -1;
combo.Text = filter;
// set the position of the cursor
combo.SelectionStart = filter.Length;
combo.SelectionLength = 0;
}