C# Adding Filter to combobox dropdown list

后端 未结 2 1810
逝去的感伤
逝去的感伤 2020-12-11 13:21

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:



        
2条回答
  •  感动是毒
    2020-12-11 13:55

    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; 
    }
    

提交回复
热议问题