Search code examples
c#comboboxnullselectedvalue

Combobox returns null when value is typed


Sorry if it has some obvious solution, but I am trying to solve it for hours but could not find a solution.

I use several ComboBoxes in my WindowsFormsApplication to relate ids with names. The problem is that when a user select an item from the combobox list, it works fine, but when he types an item, the SelectedValue property of the combobox is null.

To simulate the problem, I created a from with one button and a combobox. In my actual application, I populate the comboboxes with data from tables in a sqlserver database, but for simplicity, here I populate it with a list:

public Form1()
{
    InitializeComponent();
    List<KeyValuePair<short,short>> l = new List<KeyValuePair<short,short>>();
    l.Add(new KeyValuePair<short,short>(1,10));
    l.Add(new KeyValuePair<short,short>(2,20));
    l.Add(new KeyValuePair<short,short>(3,30));
    this.comboBox1.DataSource = l;
    this.comboBox1.DisplayMember = "Value";
    this.comboBox1.ValueMember = "Key";
}

private void button1_Click(object sender, EventArgs e)
{
    if (this.comboBox1.SelectedValue == null)
        MessageBox.Show("NULL");
    else
        MessageBox.Show(this.comboBox1.SelectedValue.ToString());
}

For example, when user select the second item (20) from the list and clicks on the button, messagebox shows 2 as it is expected, but if he types the number 20 into the combobox, the SelectedValue is null.

This problem could be solved by changing the style of combobox:

this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

But it prevents user to type into the combobox, so I am forced to use the default ComboBoxStyle.DropDown.


Solution

  • Thats because the combo box does not select the item that you have typed. Add this option

    comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
    

    Then it will select the item when ever it was able to find it.

    By default it is set to AutoCompleteMode.None.

    (I think) This is mainly designed for suggestions but it can solve your problem here. also if you want to show the suggestions:

    comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
    

    by default it is set to AutoCompleteSource.None.

    https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.autocompletemode%28v=vs.110%29.aspx