2014-11-06 36 views
6

我創建了一個包含三個值的組合框。我想這是沒有選擇項目時會打開一個消息框,所以我想這一點:檢查組合框的值是否爲空

if (comboBox1.SelectedItem == null) 
{ 
    MessageBox.Show("Please select a value"); 
    return; 
} 

這工作正常,但只有當我點擊進入該領域的組合框。當我不接觸它時,程序將在沒有消息框的情況下開始。怎麼了?

+0

何種標準觸發此代碼的事件?它是在Form_Load還是? – HABJAN 2014-11-06 07:18:22

+0

不,我已經將它放在點擊按鈕的位置來運行程序 – uzi42tmp 2014-11-06 07:26:28

回答

11

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

1

我思,這是一個:

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 
} 
1

的代碼應該工作。雖然我也將設置的SelectedIndex以及......

if (this.comboBox1.SelectedItem == null || this.comboBox1.SelectedIndex == -1) 

你的意思是「當我別碰它,程序將沒有消息框。開始怎麼啦?」有沒有與相關的任何代碼「摸」

+0

我的意思是我必須先點擊進入Box的字段。 – uzi42tmp 2014-11-06 07:35:14

+0

你在哪裏初始化組合框...? – liuzhidong 2014-11-06 07:38:20

2

使用

if (comboBox1.SelectedIndex == -1) 
{ 
    MessageBox.Show("Please select a value"); 
    return;   
} 

注:當的SelectedValue是空白的,只有當FormattingEnabled是真實的SelectedIndex將被設置爲-1。見here

1

檢查下拉列表中選擇的指數值等於-1

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