gwt
gwt

Reputation: 2413

How to add several buttons and their click events dynamically in c# code behind?

Hi I want to add several buttons and their click events dynamically to my windows forms application in my code behind where my buttons will execute System.Diagnostics.Process.Start(targetURL); how can I acheieve this ?

Upvotes: 1

Views: 1786

Answers (4)

DaveShaw
DaveShaw

Reputation: 52798

You just need to create the button, set it's properties and event handlers and then add it to the Controls collection on the form.

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);
}

Upvotes: 4

M0-3E
M0-3E

Reputation: 1052

You could write a user control that contains a textbox "txbURL", a button "btnNavigateToURL" and write the eventhandler of your button, to execute your code (System.Diagnostics.Process.Start(targetURL);)

Once you've done that, it's easy to add your control to your form on runtime, writing some code like this (don't have a c# editor right now, so you may have to verify the code)

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

that's it.

Upvotes: 2

Paolo Moretti
Paolo Moretti

Reputation: 55956

You can add any control you like to the Controls collection of the form:

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();
}

When adding several controls to a parent control, it is recommended that you call the SuspendLayout method before initializing the controls to be added. After adding the controls to the parent control, call the ResumeLayout method. Doing so will increase the performance of applications with many controls.

Upvotes: 2

Oscar
Oscar

Reputation: 13960

Declare your buttons variables.

Add the event handlers

Add them to the form Controls property.

Profit

Upvotes: 2

Related Questions