如何在c#代码后面动态添加几个按钮及其单击事件?

时间:2012-09-05 08:24:20

标签: c# winforms code-behind

您好我想在我的代码后面动态地将几个按钮及其点击事件添加到我的Windows窗体应用程序中,我的按钮将在其中执行System.Diagnostics.Process.Start(targetURL);我该如何实现这一点?

4 个答案:

答案 0 :(得分:4)

您只需创建按钮,设置其属性和事件处理程序,然后将其添加到表单上的Controls集合中。

var button = new Button();
try
{
    button.Text = "Button 1";
    button.Click += (sender, e) => System.Diagnostics.Process.Start(targetURL);
    //Or if you don't want to use a lambda and would rather have a method;
    //button.Click += MyButton_Click;
    Controls.Add(button);
}
catch
{
    button.Dispose();
    throw;
}

//Only needed when not using a lambda;
void MyButton_Click(Object sender, EventArgs e)
{
    System.Diagnostics.Process.Start(targetURL);
}

答案 1 :(得分:2)

您可以将任何您喜欢的控件添加到表单的Controls集合中:

var targetURL = // ...

try
{
    SuspendLayout();

    for (int i = 0; i < 10; i++)
    {
        var button = new Button();
        button.Text = String.Format("Button {0}", i);
        button.Location = new Point(0, i * 25);
        button.Click += (object sender, EventArgs e) => System.Diagnostics.Process.Start(targetURL);
        this.Controls.Add(button);
    }
}
finally
{
    ResumeLayout();
}

向父控件添加多个控件时,建议您在初始化要添加的控件之前调用SuspendLayout方法。将控件添加到父控件后,调用ResumeLayout方法。这样做可以提高具有许多控件的应用程序的性能。

答案 2 :(得分:2)

声明你的按钮变量。

添加事件处理程序

将它们添加到表单控件属性。

利润

答案 3 :(得分:2)

您可以编写一个包含文本框“txbURL”的用户控件,一个按钮“btnNavigateToURL”并编写按钮的事件处理程序,以执行您的代码(System.Diagnostics.Process.Start(targetURL);)

完成后,可以很容易地在运行时将控件添加到表单中,编写一些这样的代码(现在没有ac#编辑器,所以你可能需要验证代码)

MyControlClassName userControl = new MyControlClassName(string targetUrl);
userControl.Parent = yourForm;
yourForm.Controls.Add(userControl);

就是这样。