2014-04-15 87 views
3

我想獲得的ComboBoxSelectedItem的關鍵,但不弄清楚如何讓我做的是代碼,如何從ComboBox的SelectedItem中獲取密鑰?

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

回答

12

在這種情況下,字典只是鍵值對的集合,因此ComboBox上的每個項目都是KeyValuePair<YourKeyType, YourValueType>。將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;