问题描述
<pre lang="c#">
cmbSourceTag1.DataSource = new BindingSource(objSource,null);
cmbSourceTag1.DisplayMember = 价值;
cmbSourceTag1.ValueMember =Key;
如何删除和添加新的组合框的项目?
其中objSource是
cmbSourceTag1.DataSource = new BindingSource(objSource, null);
cmbSourceTag1.DisplayMember = "Value";
cmbSourceTag1.ValueMember = "Key";
how to remove and add new items to combobox ?
where objSource is
Dictionary<int, string>
我的尝试:
What I have tried:
cmbSourceTag2.Items.RemoveAt(((KeyValuePair<int, string>)cmbSourceTag2.Items[2]).Key);
它会抛出错误
有人有想法从组合框中删除和添加项目吗?
谢谢
it will throw the error
anyone have an idea to remove and add item from combobox?
Thanks
推荐答案
private void RemoveFromDictionary_Click(Object sender, EventArgs e) {
if (cbx.SelectedIndex != -1) {
KeyValuePair<int, string> item = (KeyValuePair<int, string>)cbx.SelectedItem;
// Remove from dictionary
dic.Remove(item.Key);
// Force the BindingSource to recreate the intermediate BindingList
// and refresh the combobox
cbxBindingSource.DataSource = null;
cbxBindingSource.DataSource = dic;
}
}
如果您可以重新设计程序直接使用BindingList而不是字典,代码将变得更加简单。 />
If you can redesign your program to use a BindingList directly instead of the dictionary, the code will become much simpler.
private void RemoveFromList_Click(Object sender, EventArgs e) {
if (cbx.SelectedIndex != -1) {
bindlist.RemoveAt(cbx.SelectedIndex);
}
}
Alan。
Alan.
这篇关于当数据源是字典< int,string>时,清除并添加组合框项目。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!