Search code examples
c#dictionarycomboboxbindingsource

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


I have the following code in a Windows Form

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?

If I put data in the Dictionary, everything is Ok.

EDIT: Solution is in the comment of the answer (until we have better)


Solution

  • 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.