[英]Check if combobox value is empty
I have created a ComboBox with three values.我创建了一个包含三个值的 ComboBox。 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)
The code should work.代码应该可以工作。 Although I will also set SelectedIndex as well......虽然我也会设置 SelectedIndex ......
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
检查下拉选择的索引值是否等于-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 . ComboBox 显示一个与 ListBox 结合的文本框,它使用户能够从列表中选择项目或输入新值。 Conditionally testing SelectedItem or SelectedIndex will not handle the case of the user entering a new value from another input device like a keyboard.有条件地测试 SelectedItem 或 SelectedIndex 不会处理用户从另一个输入设备(如键盘)输入新值的情况。 Use string.IsNullOrEmpty(comboBox1.Text) to handle all input/selection cases.使用 string.IsNullOrEmpty(comboBox1.Text) 处理所有输入/选择情况。
try this is the :试试这是:
if ((comboBox.SelectedValue == null) || string.IsNullOrEmpty(comboBox.Text))
{
//message no items selected
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.