当数据源是字典< int,string>时,清除并添加组合框项目。 [英] Clear and add combobox items when its datasource is dictionary<int, string>

查看:108
本文介绍了当数据源是字典< int,string>时,清除并添加组合框项目。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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

推荐答案

组合框可以使用 项集合或数据源。它们是互斥的,使用DataSource时无法修改Items集合。



正如Richard所说,你必须在数据源中添加和删除项目。



在选择字典作为原始数据源时,您已完成此任务非常复杂。字典不会直接绑定到组合框,因为它没有实现所需的IList接口。 BindingSource实际上创建了一个中间System.ComponentModel.BindingList(用字典中的KeyValuePairs填充),然后将其分配给ComboBox.DataSource。实际上字典根本没有绑定到组合框。



让我们假设有一个按钮从组合框中删除所选项目。这是它的点击处理程序的代码

A combobox can use either an Items collection or a DataSource. They are mutually exclusive and the Items collection cannot be modified when a DataSource is used.

As Richard has said you must add and remove items from the datasource.

In choosing a Dictionary as the original datasource you have made this task quite complicated. A dictionary will not bind to a combobox directly as it does not implement the required IList interface. The BindingSource actually creates an intermediate System.ComponentModel.BindingList (populated with KeyValuePairs from dictionary) and then assigns that to the ComboBox.DataSource. In effect the dictionary is not bound to the combobox at all.

Lets assume there is a button which removes the selected item from the combobox. This is the code for it's click handler
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.


这篇关于当数据源是字典&lt; int,string&gt;时,清除并添加组合框项目。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆