combobox automatically selecting a value

2.3k Views Asked by At

I using a System.Windows.Forms.ComboBox and I'm getting some weird unexpected behavior. In c#, I am dynically adding a few comboBoxes to my form and binding them to a list. The only fields I'm setting are DataSource,ValueMember, and DisplayMember. For some reason, after I bind to the list, the first item is selected. I cannot figure out what's going on.

My code looks like this:

 Control c = new System.Windows.Forms.ComboBox();

Looping through all my controls,

if (c?.GetType() == typeof (ComboBox))
{
    BindComboBox((ComboBox) c);
}


private void BindComboBox(ComboBox sender)
{
    DataTable table = DataGateway.GetTables(1);
    sender.DataSource = table;
    sender.ValueMember = "ID";
    sender.DisplayMember = "Name";

    //sender.SelectedIndex = -1; I tried with this and without this
}   

I also tried a second method but the same thing is happening -

private void BindComboBox(ComboBox sender)
{

    List<string> hiStrings = new List<string>() {"hi", "hello", "whats up"};
    sender.DataSource = hiStrings;

}
1

There are 1 best solutions below

1
On

First value is selected but is default behavior when You don't nothing change in ComboBox class settings

Modify the second method:

private void BindComboBox(ComboBox sender)
{

    List<string> hiStrings = new List<string>() {"hi", "hello", "whats up"};
    sender.DataSource = hiStrings;

    sender.SelectedItem = null;
}

And this give You empty ComboBox on Form

This solution is working and I tested.

Some helps links:

How to deselect the text of a combobox

Test method:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void comboBox1_MouseLeave(object sender, EventArgs e)
        {
          var comboBox = sender as ComboBox;

          this.TestMethod(comboBox);
        }

        private void TestMethod(ComboBox d)
        {
            var list = new List<string>() {"hi", "hello", "whats up"};
            d.DataSource = list;
            d.SelectedItem = null;
        }
    }