【问题标题】:Dynamically add click event to other forms将点击事件动态添加到其他表单
【发布时间】:2013-04-16 16:08:45
【问题描述】:

我想动态添加一个从form1到form2的点击事件。

这是我在 form1 中的代码:

Form2 frm = new Form2();
string title =(string)listBox1.SelectedItem;
TabPage myTabPage = new TabPage(title);
frm.tabControl1.TabPages.Add(myTabPage);
//create button and it's event
Button button1 = new Button();
button1.Click += new System.EventHandler(button1_Click);
button1.Location = new Point((myTabPage.Width/2)-(button1.Width/2),myTabPage.Height-30);
button1.Text = "Click On Me!";
myTabPage.Controls.Add(button1);
frm.Show();

我收到以下错误: 当前上下文中不存在名称“button1_Click”

请帮忙。

【问题讨论】:

  • 您是否定义了 button1_Click 新表单的任何位置?如果不是,则必须在将其绑定到任何按钮单击事件之前对其进行定义。

标签: c# events button


【解决方案1】:

您需要创建您的button1_Click 事件处理程序。目前,您正在将事件处理程序分配给“调用 button1_Click”的按钮,但实际上尚未创建要调用的“button1_Click”方法。

private void button1_Click(object sender, EventArgs e) 
{
   //code to call when the button is clicked.  
}

从评论更新。您可以创建一个anonymous method

button1.Click += (s,e) =>
     { 
         //code to call when the button is clicked. 
     };

【讨论】:

  • 是的,我知道,但我必须将它添加到 form2 中?它不工作:(
【解决方案2】:

您能否提前创建按钮并禁用并使其不可见,直到您想使用它?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    相关资源
    最近更新 更多