简体   繁体   English

如何在按钮后面动态添加代码

[英]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.

相关问题 如何将ID动态添加到文本框并在Webforms中的代码后面检索 - How to dynamically add Id to a Textbox and retrive it in code behind in webforms 如何从后面的代码动态添加Repeater控件? - How to add Repeater control dynamically from code behind? 如何在后面的代码上动态添加asp:TextBox? (不是TextArea) - How to add asp:TextBox dynamically on code behind ? (Not TextArea) 如何在 C# 代码后面的按钮中添加 StackPanel - How to add a StackPanel in a Button in C# code behind 在后面的代码中将RequiredFieldValidator添加到动态创建的控件中 - Add RequiredFieldValidator to dynamically created control in code behind 如何在html按钮后面编码? - how to code behind a html button? “添加到我的硬盘”按钮后面的代码 - Code Behind the “Add to My Drive” Button 如何获取从事件处理程序中的背后代码动态生成的链接按钮ID - How to get link button id that is generated dynamically from code behind in the event handler 如何动态更改类后面的WebService代码? - How to change WebService code behind class dynamically? 如何在后面动态创建的radgrid代码中添加Cell Formatting事件方法? - How to add Cell Formatting event method to dynamically created radgrid code behind?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM