Thomas
Thomas

Reputation: 1126

How do I create a event handler for a code that draws out the GUI for Windows Form Application

I am currently using the code in main.cs to draw out the GUI instead of using the [design] form. I understand that if you are using the [design] file to draw your GUI, all you have to do to create a event handler is just to double click the object.

But since I am using the code the draw out the labels/buttons, how do I do a event handler for that particular button/object?

p.Controls.Add(new Button
         {
            Text = "Clear",
            Name = "btnClear",
            Location = new Point(416, 17)
        });

e.g. how do I add an event handler for the above code?c

Upvotes: 1

Views: 164

Answers (1)

Mark Byers
Mark Byers

Reputation: 838086

You need to first create an instance of your button and assign it to a variable. Then you can add an event handler by calling += on the Click event of the button.

// This is a method body
{
    Button btnClear = new Button
    {
        Text = "Clear",
        Name = "btnClear",
        Location = new Point(416, 17)
    };
    p.Controls.Add(btnClear);
    btnClear.Click += new EventHandler(btnClear_Click);
}

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

In Visual Studio, after typing btnClear.Click += you can just press Tab twice and it will add the rest of the code.

Upvotes: 2

Related Questions