为什么我的表单控件都没有被识别为ComboBoxes?

时间:2012-07-18 18:11:26

标签: c# winforms dynamic combobox event-handling

我正在制作一个组合框" readonly"这样:

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

...但if条件永远不等于true;表格上有几个ComboBox ... ???

2 个答案:

答案 0 :(得分:5)

ComboBox很可能在其他面板中。

尝试递归地浏览它们:

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 :(得分:1)

虽然它在begin {并调用c.gettype()

上设置了一个断点

你也可能想要这样做

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

}