Add a Button Control Pragrmatically in C#
Today in C#, we will create a program that will add a button pragmatically in windows form using C#.
Now, let's start this tutorial!
1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application.
2. You don't have to design a button in your form because we will just code to have a button when loading the form.
3. Put this code in your code view.
- //set a class variable to be used during the form
- private int Count_control = 0;
- private Point Location_control = new Point(10, 50);
After that, create a method for creating a Button.
- private void create_button()
- //increment the count_control.
- Count_control += 1;
- //checking if the buttons has reached to 5 or not
- if (Count_control <= 5)
- //set a new button
- Button new_Button = new Button();
- //add the properties of the button
- new_Button.Name = "Button" + Count_control.ToString();
- new_Button.Text = "Button" + Count_control.ToString();
- new_Button.Location = new Point(Location_control.X + 10, Location_control.Y);
- new_Button.Width = 180;
- Location_control.Y += new_Button.Height + 10;
- //create the event handler
- new_Button.Click += new System.EventHandler(myButtonHandler_Click);
- //add the new button to the collection of controls
- //checking if you want to clear the controls that you have added.
- if (MessageBox.Show("You\'ve reached 5 controls. Do you want to clear controls to start again?", "Proceed", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == Windows.Forms.DialogResult.OK)
- Controls.Clear(); //clearing the control
- Count_control = 0; //returning the count_control to its default value
- Location_control = new Point(10, 50); //set a new point of the controls
- create_button(); //put a control so that you can add another controls
Then, create a subroutine that handles the click events of the Buttons.
- private void myButtonHandler_Click(object sender, EventArgs e)
- //verifying the buttons
- if (sender is Button)
- create_button(); //create a new button
Lastly, you have to put your method that you have created in the first load so that the button will appear in the Form.
- private void Form1_Load(System.Object sender, System.EventArgs e)
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware