4

のキーを取得しようとしていますがSelectedItemComboBoxコードを取得する方法がわかりません。

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

このようにコンボボックスをバインドし、

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

2 に答える 2

14

このような場合、辞書は単にキーと値のペアのコレクションであるため、 の各項目ComboBoxKeyValuePair<YourKeyType, YourValueType>. a にキャストSelectedItemするKeyValuePair<YourKeyType, YourValueType>と、キーを読み取ることができます。

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

または、より簡単な方法は、SelectedValueプロパティを使用することです。

// get ComboBox from sender
ComboBox comboBox = (ComboBox) sender;

// get selected Key
YourKeyType selectedKey = (YourKeyType) comboBox.SelectedValue;
于 2014-04-15T21:50:24.087 に答える