我想动态地将一个click事件从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”这个名称在当前上下文中不存在
请帮忙。
答案 0 :(得分:3)
您需要创建button1_Click
事件处理程序。目前,您正在将事件处理程序分配给“call 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.
};
答案 1 :(得分:-1)
您是否可以提前创建按钮并禁用并隐藏,直到您想要使用它为止?