2015-02-11 82 views
1

基本上在下面的代碼中,我試圖通過數組循環,如果組合框中的當前文本不匹配數組中的任何東西,它會引發錯誤。但是我無法讓它觸發事件TextChanged事件。組合框C#的TextChanged事件#

任何幫助是極大的讚賞在屬性窗口

string[] SRtier1 = { "Option1", "Option2", "Option3", "Option4", "Option5" };   

private void SRcmb_tier1_TextChanged(object sender, EventArgs e) 
    { 
     //Loop SRtier1 Array to ComboBox 
     for (int i = 0; i < SRtier1.Length; i++) 
     { 
      if (SRcmb_tier1.Text != SRtier1[i]) 
      { 
       MessageBox.Show("Please select one of the options provided."); 
      } 
     } 
    } 
+2

仔細檢查您的組合框是否與屬性窗口中的「SRcmb_tier1_TextChanged」事件綁定。 – 2015-02-11 10:46:33

回答

1

首先,你必須錯誤的循環實現:在你的代碼你渴望解僱消息SRtier1.Length次,你想要的可能是,檢查輸入並激發消息一次:

private void SRcmb_tier1_TextChanged(object sender, EventArgs e) 
{ 
    Boolean found = false; 

    for (int i = 0; i < SRtier1.Length; i++) 
    { 
     if (SRcmb_tier1.Text == SRtier1[i]) 
     { 
      found = true; 
      break; 
     } 
    } 

    if (!found) 
     MessageBox.Show("Please select one of the options provided."); 
} 

更好的解決方案是使用的Linq

private void SRcmb_tier1_TextChanged(object sender, EventArgs e) { 
    if (!SRtier1.Any(item => item == SRcmb_tier1.Text)) 
     MessageBox.Show("Please select one of the options provided."); 
    } 

最後,檢查是否SRcmb_tier1_TextChanged是assinged到SRcmb_tier1TextChanged馮v在註釋中說。

+0

非常感謝,完美的作品! – SourCitrix 2015-02-11 11:22:49

1

檢查在事件如果u在框TextChanged有什麼