[英]How to dynamically add a code behind for button
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);
I have positioned the button, what property would I use to add code behind the button? 我已经定位了按钮,我将使用什么属性在按钮后面添加代码?
Pretty easy: 相当容易:
bn.Click += MyClick;
...
private void MyClick(object sender, EventArgs e) {
MessageBox.Show("hello");
}
Here you're registering a click event and specify the code that runs when the event fires. 在这里,您要注册一个click事件,并指定事件触发时运行的代码。
You need to do some stuff to prep the button on the form (referenced by this
in the example, taken from http://msdn.microsoft.com/en-us/library/y53zat12.aspx .) 你需要做一些东西来准备窗体上的按钮(通过引用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();
}
There is really no "code behind" -- the Button is the object, use it as you wish. 确实没有“背后的代码”-Button是对象,可以根据需要使用它。 Presumably you want to subscribe to the click event: 大概您想订阅click事件:
bn.Click += new System.EventHandler(this.bnClickListener);
private void bnClickListener(object sender, EventArgs e)
{
// Stuff to do when clicked.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.