Search code examples
c#winformseventscombobox

Distinguish between clicking the displayed item and clicking an item in the drop-down list in a ComboBox


I would like to know how to distinguish between clicking the displayed item and clicking one of the items in the drop-down list of the ComboBox.


Solution

  • ... distinguish between clicking the displayed item and clicking one of the items in the drop-down list

    I assume that you want to know if the operator re-selects the last selected items (which is the displayed item), or selects a new item (which is in the drop-down list.

    You need a property to access the item that the operator selected:

    private MyType SelectedItem => (MyType)this.comboBox1.SelectedValue;
    
    private MyType LastProcessedSelectedItem {get; set;} = null;
    
    private void OnOperatorSelectedItem(MyType selectedItem)
    {
        if (this.LastProcessedSelectedItem != selectedItem)
        {
            this.OperatorSelectedDropDown();
        }
        else
        {
             this.OperatorSelectedDisplayed();
        }
        this.LastProcessedSelectedItem = selectedItem;
    }
    
    private void OnComboBox1_Clicked(object sender, ...)
    {
        MyType selectedItem = this.SelectedItem;
        OnOperatorSelectedItem(selectedItem);
    }