user3818701
user3818701

Reputation: 93

Can't click programmatically added buttons

I'm programmatically adding a button to a form, and for some reason I can't click it. Why not?

private Button btnBrowser = new Button();

this.btnBrowser.Text = "Open Browser";
this.btnBrowser.Location = new System.Drawing.Point(55, 45);
this.btnBrowser.Size = new System.Drawing.Size(70, 30);

This adds the button to the form, but I can't click it.

private void btnBrowser_Click(object sender, EventArgs e)
{
    MessageBox.Show("test");
}

Upvotes: 2

Views: 76

Answers (2)

codebased
codebased

Reputation: 7073

var btnBrowser  = new Button();
btnBrowser.Text = "Open Browser";
btnBrowser.Location = new System.Drawing.Point(55, 45);
btnBrowser.Size = new System.Drawing.Size(70, 30);
btnBrowser.Click += (o, evt) =>
{
    MessageBox.Show("test");
};

Upvotes: 2

LarsTech
LarsTech

Reputation: 81620

Make sure you add it to the form, and add the event handler:

this.Controls.Add(btnBrowser);
btnBrowser.Click += btnBrowser_Click;

Upvotes: 7

Related Questions