Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't click programmatically added buttons

Tags:

c#

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");
}
like image 783
user3818701 Avatar asked Feb 14 '26 08:02

user3818701


2 Answers

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

this.Controls.Add(btnBrowser);
btnBrowser.Click += btnBrowser_Click;
like image 186
LarsTech Avatar answered Feb 15 '26 21:02

LarsTech


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");
};
like image 21
codebased Avatar answered Feb 15 '26 22:02

codebased



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!