Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 377
Hassaan Avatar asked Dec 03 '22 19:12

Hassaan


2 Answers

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;
like image 123
Michael Gunter Avatar answered Jan 05 '23 16:01

Michael Gunter


Try this:

string key = ((KeyValuePair < string, string > )comboBox1.SelectedItem).Key;

like image 29
Chhornkimchheng Avatar answered Jan 05 '23 16:01

Chhornkimchheng