0
votes

My question is "Is there a way to bind data to a comboBox without the selectedItem and text values being changed / populated?" (I want the comboBox to stay blank)

This is an EXAMPLE of what I am doing:

        Dictionary<int,string> test = new Dictionary<int,string>();
        test.Add(1, "Company1");
        test.Add(2, "Company2");
        test.Add(3, "Company3");
        test.Add(4, "Company4");
        test.Add(5, "Company5");
        test.Add(6, "Company6");

        var list = test.Select(x => new { CompanyName = x.Value }).ToList();

        comboBox1.DataSource = list;
        comboBox1.DisplayMember = "CompanyName";
        comboBox1.ValueMember = "CompanyName";
        comboBox1.SelectedItem = null;

If you run this code, it works fine, because it loads so fast, it looks like the comboBox stays blank.

However, if you step through the code, you will see that the SelectedItem and Text values get changed when the DataSource is assigned to "list".

My actual LINQ query is quite a bit bigger, and thus slower to load. My comboBox "flashes" the Text value before it gets cleared out, and I want to remove this ugly flash.

I have tried different combinations of setting SelectedItem and Text values to null (or "") before and after the DataSource assignment, but I cannot get the "flash" to go away.

Any suggestions are greatly appreciated! =)

EDIT: I also want to add that this only happens on the initial form load... If I change the bindingsource and then reset back to my original (running the exact same code again), it doesn't "flash"... Not sure if this helps or makes a difference...

5

5 Answers

1
votes

Another simple suggestion would be to just add the blank CompanyName as the first item in a list

list.Insert(0, "");
1
votes

Try using comboBox1.SuspendLayout() and comboBox1.ResumeLayout() around your data binding code. The first should prevent it from updating at all until the second is called.

1
votes

Add a null-Reference to your List as the first list-element before you set comboBox1.DataSource.

 var list = test.Select(x => new { CompanyName = x.Value }).ToList();
 list.Insert(0, null);
 comboBox1.DataSource = list;
0
votes

I was running into the same issue, but I couldn't add an empty item so what I did was:

comboBox.ForeColor = comboBox.BackColor;
//set the combobox datasource
comboBox.ForeColor = SystemColors.WindowText;

That makes the combo box appear to be blank while setting the datasource without adding an empty item.

0
votes

This worked for me: removing the bindings, and then adding them back after setting the DataSource:

Binding[] bindings = new Binding[combo.DataBindings.Count];
combo.DataBindings.CopyTo(bindings, 0);
combo.DataBindings.Clear();
combo.DataSource = datasource;
combo.SelectedIndex = -1;
foreach (Binding b in bindings)
{
    combo.DataBindings.Add(b);
}