[英]Check if combobox value is empty
我創建了一個包含三個值的 ComboBox。 我希望在沒有選擇任何項目時打開一個消息框,所以我嘗試了這個:
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Please select a value");
return;
}
這工作正常,但前提是我單擊組合框中的字段。 當我不觸摸它時,程序將在沒有消息框的情況下啟動。 怎么了?
if (string.IsNullOrEmpty(comboBox1.Text))
或if (comboBox1.SelectedIndex == -1)
用
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("Please select a value");
return;
}
注意:僅當 FormattingEnabled 為 true 時,SelectedIndex 才會在 SelectedValue 為空時設置為 -1。 見這里。
代碼應該可以工作。 雖然我也會設置 SelectedIndex ......
if (this.comboBox1.SelectedItem == null || this.comboBox1.SelectedIndex == -1)
你的意思是“當我不觸摸它時,程序將在沒有消息框的情況下啟動。怎么了?” 是否有任何與“觸摸它”相關的代碼
檢查下拉選擇的索引值是否等於-1
if (Comboboxid.SelectedIndex == -1){
MessageBox.Show("Your message.");
}
我認為這是一個:
if(comboBox.SelectedItems==null) //or if(comboBox.SelectedItems==-1)
{
//show no item was selected from comboBox
}
或者
if(comboBox.SelectedItems.Count==0)
{
//message no items selected
}
ComboBox 顯示一個與 ListBox 結合的文本框,它使用戶能夠從列表中選擇項目或輸入新值。 有條件地測試 SelectedItem 或 SelectedIndex 不會處理用戶從另一個輸入設備(如鍵盤)輸入新值的情況。 使用 string.IsNullOrEmpty(comboBox1.Text) 處理所有輸入/選擇情況。
試試這是:
if ((comboBox.SelectedValue == null) || string.IsNullOrEmpty(comboBox.Text))
{
//message no items selected
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.