2012-07-18 107 views
1

我做这样一个组合框“只读”:为什么我的窗体控件没有被识别为ComboBox?

private void comboBox1_SelectedValueChanged(object sender, EventArgs e) 
{ 
    // for this to work, set the comboboxes' Tag to its SelectedIndex after setting that 
    ComboBox cb = sender as ComboBox; 
    int validSelection = Convert.ToInt32(cb.Tag); 
    if (cb.SelectedIndex != validSelection) 
    { 
     cb.SelectedIndex = validSelection; 
    } 
} 

...然后试图将所有的组合框的形式,以该处理程序是这样的:

foreach (Control c in this.Controls) 
{ 
    if (c is ComboBox) 
    { 
     (c as ComboBox).SelectedValueChanged += comboBox1_SelectedValueChanged; 
    } 
} 

......但是,如果条件永远不等于真实;窗体上有几个ComboBox ...?

+1

他们是在面板内部?顺便提一下断点。 – Silvermind 2012-07-18 18:17:01

+0

我现在看到,由于我的大多数控件都在面板上,我必须在this.panel1.Controls中检查foreach控件。有没有办法检查窗体上的所有控件,而不必指定父窗体? - 是的,Silvermind,你是对的(我没有看到你的评论,直到我添加了这一个,它刷新)。 – 2012-07-18 18:25:58

回答

5

的组合框最有可能其他面板内。

试图通过他们去递归:

private void button1_Click(object sender, EventArgs e) { 
    ChangeCombos(this); 
} 

private void ChangeCombos(Control parent) { 
    foreach (Control c in parent.Controls) { 
    if (c.Controls.Count > 0) { 
     ChangeCombos(c); 
    } else if (c is ComboBox) { 
     (c as ComboBox).SelectedValueChanged += comboBox1_SelectedValueChanged; 
    } 
    } 
} 
1

一步虽然它设置一个断点上开始{并调用c.gettype()

还您可能要做到这一点

if(c.gettype() == typeof(ComboBox)) 
{ 

} 
相关问题