Check if combobox value is empty

醉酒当歌 提交于 2020-04-08 09:55:34

问题


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?


回答1:


if (string.IsNullOrEmpty(comboBox1.Text)) or if (comboBox1.SelectedIndex == -1)




回答2:


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.




回答3:


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"




回答4:


Check the selected index value of dropdown equals -1

if (Comboboxid.SelectedIndex == -1){
    MessageBox.Show("Your message.");
}



回答5:


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 
}



回答6:


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.



来源:https://stackoverflow.com/questions/26773729/check-if-combobox-value-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!