How to dynamically add button and click event in C#
By FoxLearn 7/18/2024 8:08:26 AM 14.24K
In C#, you can dynamically add a button click event handler by creating a method that will handle the click event and then assigning this method to the button's Click event at runtime.
C# Dynamically add button click event
Drag and drop a Button control from the Visual Studio toolbox into your form designer, then add a click event handler to the button control.
Each time you click the add button, a button is dynamically created and added to the form with the click event.
C# Dynamically add button to form
int index = 1; //c# dynamic add button private void btnAddButton_Click(object sender, EventArgs e) { string name = $"Button_{index++}"; // Create a new button Button btn = new Button() { Name = name, Text = name }; btn.Size = new System.Drawing.Size(100, 25); btn.Location = new System.Drawing.Point(190, index * 35); // Attach the event handler to the button btn.Click += Btn_Click; // Add the button to the form this.Controls.Add(btn); }
And don't forget to implement Btn_Click event handler.
// Event handler method for the dynamic button private void Btn_Click(object sender, EventArgs e) { Button button = (sender as Button); MessageBox.Show($"{button.Name} clicked.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); }
In this example, we create a new button dynamically and then attach the Btn_Click
method to its Click
event using the +=
operator. When the button is clicked, the Btn_Click
method will be invoked.
Categories
Popular Posts
Responsive Animated Login Form
11/11/2024
Carpatin Admin Dashboard Template
11/17/2024
Plus Admin Dashboard Template
11/18/2024