检测Form中的其他类ComboBox更改

时间:2012-05-25 17:57:56

标签: c#

我想检测ComboBox selectedindex更改。 组合框位于不同的类,然后是Form类:

class Analyze
    {
        public Analyze(Form theform)
        {
            size = new ComboBox();
            size.Location = new Point(100,100);
            size.Name = "matrixsize";
            size.Size= new Size(200,100);
            size.Items.AddRange(matrix_sizes);
            theform.Controls.Add(size);
        }
        private string[] matrix_sizes = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
        private ComboBox size;
    }

我在这里创建一个Analyze类型的新对象:

private void Analyze_Click(object sender, EventArgs e)
{
    Analyze analyze = new Analyze(this);
}

现在我想检测Analyze.size中值的变化,我该怎么做?访问大小组合框的正确方法是什么?

提前感谢。

1 个答案:

答案 0 :(得分:1)

只需添加自己的处理程序:

class Analyze {
  public event EventHandler SelectedIndexChanged;

  public Analyze(Form theform) {

    ...
    size.SelectedIndexChanged += size_SelectedIndexChanged;
    theform.Controls.Add(size);
  }

  void size_SelectedIndexChanged(object sender, EventArgs e) {
    if (SelectedIndexChanged != null) {
      SelectedIndexChanged(sender, e);
    }
  }
}

然后在调用表单上删除你的事件:

private void Analyze_Click(object sender, EventArgs e)
  Analyze analyze = new Analyze(this);
  analyze.SelectedIndexChanged += analyze_SelectedIndexChanged;
}

void analyze_SelectedIndexChanged(object sender, EventArgs e) {
  // do something
}