How to create a button and add to it a click event handler in a WinForms application using C#

1 Answer

0 votes
namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CreateButton();
        }

        private void CreateButton()
        {
            // Create a new button
            Button myButton = new Button();

            // Set button properties
            myButton.Text = "My New Button";
            myButton.Location = new System.Drawing.Point(100, 100); // Set the position on the form
            myButton.Size = new System.Drawing.Size(110, 40); // Set the size of the button

            // Add a click event handler
            myButton.Click += new EventHandler(MyButton_Click);

            // Add the button to the form's controls
            this.Controls.Add(myButton);
        }

        private void MyButton_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button clicked!");
        }
    }
}



/*
run:
 
 
*/

 



answered Apr 2 by avibootz
...