I have created a ComboBox with three values. I wanted that a message box opens when no item is selected so I tried this:
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Please select a value");
return;
}
That works fine but only if I click into the field in the combobox. When I dont touch it, the program will start without message box. Whats wrong?
if (string.IsNullOrEmpty(comboBox1.Text))
或if (comboBox1.SelectedIndex == -1)
Use
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("Please select a value");
return;
}
Note: SelectedIndex will be set to -1 when SelectedValue is blank ONLY when FormattingEnabled is true. See here .
The code should work. Although I will also set SelectedIndex as well......
if (this.comboBox1.SelectedItem == null || this.comboBox1.SelectedIndex == -1)
you mean "When I dont touch it, the program will start without message box. Whats wrong?" is there any code related with "touch it"
Check the selected index value of dropdown equals -1
if (Comboboxid.SelectedIndex == -1){
MessageBox.Show("Your message.");
}
Ithink this is the one :
if(comboBox.SelectedItems==null) //or if(comboBox.SelectedItems==-1)
{
//show no item was selected from comboBox
}
or
if(comboBox.SelectedItems.Count==0)
{
//message no items selected
}
A ComboBox displays a text box combined with a ListBox, which enables the user to select items from the list or enter a new value . Conditionally testing SelectedItem or SelectedIndex will not handle the case of the user entering a new value from another input device like a keyboard. Use string.IsNullOrEmpty(comboBox1.Text) to handle all input/selection cases.
try this is the :
if ((comboBox.SelectedValue == null) || string.IsNullOrEmpty(comboBox.Text))
{
//message no items selected
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.