Reputation: 4273
I want the user to not be able to select an "empty" choice from the ComboBox (drop down style). This can be done if the user deletes the text of the ComboBox with his keyboard. I have tried having a SelectedIndexChanged
event and try to detect if the user sets the value to null and change it to 0
instead. BUT, this event doesn't trigger when the value is set to null (even after the user hits enter from his keyboard).
Any possible solutions ?
Upvotes: 3
Views: 8526
Reputation: 19404
I have feeling that you, may be, struggling with UI logic. If you don't want to have empty items, than don't add one. But often it is useful to have an "empty item". One reason, if you have something selected for user, user just clicks "save" or something without changing that value and having wrong value.
Use SelectedIndex
property to determine what selected during verification.
// init
cbo.comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
cbo.Items.Add("Select Letter") // first "empty" item
cbo.Items.Add("A")
cbo.Items.Add("B")
cbo.Items.Add("C")
// ---
void Save()
{
if (cbo.SelecteIndex < 1)
{
MessageBox.Show("Please select letter");
return;
}
// "save" code here
}
Upvotes: 0
Reputation: 37908
Set the DropDownStyle
of your ComboBox to DropDownList
:
and in your form's constructor add something like this:
yourComboBox.SelectedIndex = (yourComboBox.Items.Count > 0) ? 0: -1;
Upvotes: 5
Reputation: 2373
If you don't require a user to be able to type in custom values, you can change the drop down style to only allow the selection of items from your list. If you then set a default option, the user will never have an empty option selected.
For example:
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.SelectedIndex = 0;
Upvotes: 1