C# 如何为按钮动态添加代码

C# 如何为按钮动态添加代码,c#,winforms,C#,Winforms,我已经定位了按钮,我将使用什么属性在按钮后面添加代码?非常简单: Button bn = new Button(); bn.Location = new System.Drawing.Point(560, 350); bn.Name = "btnDelete"; bn.Text = "Delete"; bn.Size = new System.Drawing.Size(100, 50); myTabPage.Controls.Add(bn); 这里,您正在注册一个单击事件,并指定事件触发时运行

我已经定位了按钮,我将使用什么属性在按钮后面添加代码?

非常简单:

Button bn = new Button();
bn.Location = new System.Drawing.Point(560, 350);
bn.Name = "btnDelete";
bn.Text = "Delete";
bn.Size = new System.Drawing.Size(100, 50);
myTabPage.Controls.Add(bn);

这里,您正在注册一个单击事件,并指定事件触发时运行的代码。

您需要做一些工作来准备表单上的按钮(示例中的
引用此
,摘自。)

实际上没有“代码隐藏”——按钮就是对象,可以随意使用。您可能想订阅click事件:

private void AddButtons()
{
   // Suspend the form layout and add two buttons.
   this.SuspendLayout();
   Button buttonOK = new Button();
   buttonOK.Location = new Point(10, 10);
   buttonOK.Size = new Size(75, 25);
   buttonOK.Text = "OK";

   this.Controls.Add(buttonOK);
   this.ResumeLayout();
}

正是我要找的!谢谢。也值得一读
private void AddButtons()
{
   // Suspend the form layout and add two buttons.
   this.SuspendLayout();
   Button buttonOK = new Button();
   buttonOK.Location = new Point(10, 10);
   buttonOK.Size = new Size(75, 25);
   buttonOK.Text = "OK";

   this.Controls.Add(buttonOK);
   this.ResumeLayout();
}
bn.Click += new System.EventHandler(this.bnClickListener);

private void bnClickListener(object sender, EventArgs e)
{
    // Stuff to do when clicked.
}