2013-04-16 72 views
0

我想动态地将点击事件从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”这个名字不会在目前情况下

请帮忙存在。

+1

哟定义button1_Click在新表单上的任何地方?如果不是,则必须在将其绑定到任何按钮单击事件之前对其进行定义。 – donstack

回答

3

您需要创建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. 
    }; 
+0

是的,我知道,但我必须将它添加到form2?它不工作:( – reza

-1

您能否提前创建按钮并禁用并隐藏,直到您想使用它?

相关问题