2015-02-11 75 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有什么