1

我正在以这种方式制作一个“只读”组合框:

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;表单上有几个 ComboBoxes ......???

4

2 回答 2

5

ComboBoxes 最有可能在其他面板中。

尝试递归地遍历它们:

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;
    }
  }
}
于 2012-07-18T18:26:35.443 回答
1

尽管它在 begin { 上设置了一个断点并调用 c.gettype()

你也可能想这样做

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

}
于 2012-07-18T18:16:33.473 回答