Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add a code behind for button

Tags:

c#

winforms

Button bn = new Button();
bn.Location = new System.Drawing.Point(560, 350);
bn.Name = "btnDelete";
bn.Text = "Delete";
bn.Size = new System.Drawing.Size(100, 50);
myTabPage.Controls.Add(bn);

I have positioned the button, what property would I use to add code behind the button?

like image 355
Brandon Avatar asked Apr 28 '26 00:04

Brandon


1 Answers

Pretty easy:

bn.Click += MyClick;

...

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

Here you're registering a click event and specify the code that runs when the event fires.

like image 139
Jay Riggs Avatar answered Apr 29 '26 13:04

Jay Riggs



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!