简体   繁体   English

如何在运行时创建的控件上添加事件

[英]How to add event on control created during runtime

I want to create click event on buttons, (2 Buttons are creating during runtime) 我想在按钮上创建click事件,(在运行时创建了2个按钮)

I am using this to create buttons: 我正在使用它来创建按钮:

private void Form1_Load(object sender, EventArgs e)
{
    for (int k = 0; k < 2; k++)
    {
        Button Btn = new Button();
        Btn.Name = "btn" + k;
        Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
        Btn.Size = new System.Drawing.Size(90, 30);
         if (k == 0)               
            Btn.Text = "Back";

         else
            Btn.Text = "Calculate";

        this.Controls.Add(Btn);
    }
}

Thanks in Advance. 提前致谢。

Simply use: 只需使用:

Btn.Click += button1_Click;

private void button1_Click(object sender, EventArgs e)
{

}

Enhance your loop like this: 像这样增强循环:

for (int k = 0; k < 2; k++)
{
    Button Btn = new Button();
    Btn.Name = "btn" + k;
    Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
    Btn.Size = new System.Drawing.Size(90, 30);
     if (k == 0)               
        Btn.Text = "Back";

     else
        Btn.Text = "Calculate";

    Btn.Click += button_Click; // <-- This is where it happens!

    this.Controls.Add(Btn);
}

Then add the event handler: 然后添加事件处理程序:

private void button_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    if (btn.Name.Equals("..."))
    {
    }
    else
    {
    }    
}

Please note that within the event handler you need to decide which button has been pressed by looking at the Name property. 请注意,在事件处理程序中,您需要通过查看Name属性来确定按下了哪个按钮。

像这样

   btn1.Click += new EventHandler(this.btn1_Click);
Btn.Click += Btn_Click;

void Btn_Click(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

in VS you can type Btn.Click += the press tab twice and it will generate the method for you. 在VS中,您可以键入Btn.Click +=两次按下选项卡,它将为您生成方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM