如何为按钮动态添加代码

时间:2011-11-21 04:55:03

标签: 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);

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

2 个答案:

答案 0 :(得分:4)

非常简单:

bn.Click += MyClick;

...

private void MyClick(object sender, EventArgs e) {
    MessageBox.Show("hello");
}

此处您正在注册点击事件,并指定事件触发时运行的代码。

答案 1 :(得分:0)

您需要执行一些操作来准备表单上的按钮(示例中的this引用,取自http://msdn.microsoft.com/en-us/library/y53zat12.aspx。)

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.
}
相关问题