Reputation: 1988
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.
Upvotes: 5
Views: 34737
Reputation: 27427
You can use combobox selected index changed event
Add this to your InitializeComboBox class
this.ComboBox1.SelectedIndexChanged +=
new System.EventHandler(ComboBox1_SelectedIndexChanged);
then in selected index changed event you can check if combox box is selected
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cbx= (ComboBox) sender;
Button1.Enabled = !string.IsNullOrEmpty(cbx.SelectedItem.ToString());
}
Upvotes: 0
Reputation: 7082
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1)
button1.Enabled = false;
else
button1.Enabled = true;
//or
//button1.Enabled = comboBox1.SelectedIndex == -1;
}
Upvotes: 0
Reputation: 526
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.
Upvotes: 8