Check if a ComboBox value is selected

32,837

Perhaps like this:

    private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox.SelectedIndex > -1)
        {
            buttonOK.Enabled = true;
        }
    }

By default a combobox's selected index is -1 (the combobox's name, which you can't reselect after choosing another index), so if you check that it's not -1 then you know a value has been selected.

However another alternative, and the one I use, is if I always want a value to be selected is to use the DropDownStyle property and set it to DropDownList. That way index 0 is selected by default and the user can only select items from the list and nothing else.

Share:
32,837
Idanis
Author by

Idanis

Updated on January 15, 2020

Comments

  • Idanis
    Idanis over 4 years

    I'm writing a form which includes some buttons and a combo box. The "Ok" button is disabled by default, and I wish to enable it only after an actual value (not the combo box's name) is selected.

    I know how to access the selected value, and how to check if a value has been selected - but these two can be done only after the form is close (using the"x" or using the "ok" button - which is disabled).

    Any ideas?

    Thanks.

    • Kevin
      Kevin over 11 years
      It's been a while for me, so I won't write an answer. But can't you check it in the property the UI object is bounded to?
    • rs.
      rs. over 11 years
      Did you try using ComboBox.SelectedIndexChanged Event
  • Mitch
    Mitch over 11 years
    This doesnt work comboBox1.SelectedValue returns null even when selecting something form the combobox.
  • Mitch
    Mitch over 11 years
    This now enables the button when nothing is selected, it's needs to enable the button only when something is selected. :P EDIT: Haha I see your ninja edit ;)
  • Mitch
    Mitch over 11 years
    I don't know why this had a +1, it actually disables the button when something is selected.
  • rs.
    rs. over 11 years
    @MitchTWC if something is selected string.IsNullOrEmpty will be false, and i'm checking !string.IsNullOrEmpty which will return true and button is enabled. Not sure why you think it will be disabled. Can you explain
  • Mitch
    Mitch over 11 years
    I just tried your example, it disables my button when I select an item from my combobox. cbx.SelectedText returns an empty string. You need to use cbx.Text