简体   繁体   English

当源为空时,绑定到字典的C#组合框获得1个项目

[英]C# Combobox binding to a Dictionary got 1 item when source empty

I have the following code in a Windows Form 我在Windows窗体中有以下代码

Dictionary<String, String> dict = new Dictionary<string, string>();
ComboBox cbo = new ComboBox();
cbo.DisplayMember = "Key";
cbo.ValueMember = "Value";  // Not used
this.Controls.Add(cbo);
BindingSource bind = new BindingSource(dict, null);
cbo.DataSource = bind;
int count = cbo.Items.Count;

Why in my case, count is 1 at the end? 为什么以我为例,计数最后是1?

If I put data in the Dictionary, everything is Ok. 如果我将数据放入字典中,一切都会好的。

EDIT: Solution is in the comment of the answer (until we have better) 编辑:解决方案在答案的评论中(直到我们有更好的选择)

Can you try changing the rows: 您可以尝试更改行:

BindingSource bind = new BindingSource(dict, null);
cbo.DataSource = bind;

to: 至:

BindingSource bind = new BindingSource();
bind.DataSource = dict;
cbo.DataSource = bind;

I tried this and the result in cbo.Items.Count was 0. 我尝试了这个, cbo.Items.Count中的结果为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM