简体   繁体   English

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

[英]Why are none of my form's controls being recognized as being ComboBoxes?

I'm making a combobox "readonly" in this way: 我以这种方式使组合框“只读”:

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

...and then trying to set all of the comboboxes on the form to that handler like this: ...然后尝试将表单上的所有组合框设置为该处理程序,如下所示:

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

...but the if condition is never equating to true; ...但是if条件永远不等于true; there are several ComboBoxes on the form...??? 表格上有几个组合框... ???

The ComboBoxes are most likely inside other panels. 组合框很可能在其他面板中。

Try going through them recursively: 尝试递归地遍历它们:

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

step though it set a breakpoint on the begin { and call c.gettype() 尽管它在开始{上设置了一个断点,并调用c.gettype()

also you might want to do this 你也可能想这样做

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM