Search code examples
c#comboboxkeyvaluepair

How to get key from SelectedItem of ComboBox?


I am trying to get the key of SelectedItem of ComboBox but do not figure it out how to get code which I have done is,

void CboBoxSortingDatagridview(ComboBox sender)
{
    foreach (var v in DictionaryCellValueNeeded)
    {
        if (!DictionaryGeneralUsers.ContainsKey(v.Key) && v.Value.RoleId == Convert.ToInt32(((ComboBox)sender).SelectedItem)) // here getting value {1,Admin} i want key value which is 1 but how?
        {
            DictionaryGeneralUsers.Add(v.Key, (GeneralUser)v.Value);
        }
    }
    dataGridViewMain.DataSource = DictionaryGeneralUsers.Values;
}  

I binded the combo box in this way,

cboRolesList.DataSource = new BindingSource(dictionaryRole, null);  
cboRolesList.DisplayMember = "Value";  
cboRolesList.ValueMember = "Key";

Solution

  • In cases like this, dictionaries are simply collections of key-value pairs, so each item on the ComboBox is a KeyValuePair<YourKeyType, YourValueType>. Cast SelectedItem to a KeyValuePair<YourKeyType, YourValueType> and then you can read the key.

    // get ComboBox from sender
    ComboBox comboBox = (ComboBox) sender;
    
    // get selected KVP
    KeyValuePair<YourKeyType, YourValueType> selectedEntry
        = (KeyValuePair<YourKeyType, YourValueType>) comboBox.SelectedItem;
    
    // get selected Key
    YourKeyType selectedKey = selectedEntry.Key;
    

    Or, a simpler way is to use the SelectedValue property.

    // get ComboBox from sender
    ComboBox comboBox = (ComboBox) sender;
    
    // get selected Key
    YourKeyType selectedKey = (YourKeyType) comboBox.SelectedValue;