【问题标题】:Dynamically added event handler? [closed]动态添加的事件处理程序? [关闭]
【发布时间】:2014-07-06 14:12:46
【问题描述】:

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

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

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

【问题讨论】:

  • 很难从巨大的文本块中解析出你想要做什么。你能重新格式化,提供一个例子,也许是一些示例代码或伪代码?

标签: c# forms


【解决方案1】:

确实知道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(可以是表单,也可以是面板)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-04
    • 2016-06-06
    • 2020-03-06
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    相关资源
    最近更新 更多