动态添加事件处理程序?

时间:2014-05-18 15:49:27

标签: c# forms

好的,没有清楚解释,如何在所有表格中搜索控件名称?

  ` void No1(Form a, int x, int y)
    {
        No2(a, x, y);
    }
    void No2(Form a, int x, int y)
    {
        Button b1 = new Button();
        b1.Location = new Point(x, y);
        b1.Click += new EventHandler(b1_click);
        b1.Name = "OgO4sEVm6asqnw";
        a.Controls.Add(b1);
    }
    void b1_click(object sender, EventArgs e)
    {
        a.Controls.RemoveByKey("OgO4sEVm6asqnw");
        No1(a, x, y);   //I have no way to get a, x and y, 
                        //since I don't know on witch form b1 is
    }`

希望这能更好地解释......

1 个答案:

答案 0 :(得分:0)

DO 通过投放b1来了解sender的格式...

void b1_click(object sender, EventArgs e)
{
    if (sender is Button)
    {
        var b1 = (Button) sender;
        b1.Parent.Controls.RemoveByKey(b1.Name);
        No1(b1.TopLevelControl, b1.Location.X, b1.Location.Y);
    }                   
}

属性TopLevelControl为您提供表单,Parent为您提供ControlContainer(可以是表单,也可以是面板)