Add a Button Control Pragrmatically in C#
Submitted by donbermoy on Saturday, July 19, 2014 - 11:58.
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.
After that, create a method for creating a Button.
Then, create a subroutine that handles the click events of the Buttons.
Lastly, you have to put your method that you have created in the first load so that the button will appear in the Form.
Output:
Best Regards,
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.
Mobile: 09488225971
Landline: 826-9296
E-mail:[email protected]
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
- //set a class variable to be used during the form
- private int Count_control = 0;
- 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
- //add the properties of the button
- new_Button.Name = "Button" + Count_control.ToString();
- new_Button.Text = "Button" + Count_control.ToString();
- new_Button.Width = 180;
- Location_control.Y += new_Button.Height + 10;
- //create the event handler
- //add the new button to the collection of controls
- Controls.Add(new_Button);
- }
- else
- {
- //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
- create_button(); //put a control so that you can add another controls
- }
- }
- }
- private void myButtonHandler_Click(object sender, EventArgs e)
- {
- //verifying the buttons
- {
- create_button(); //create a new button
- }
- }
- private void Form1_Load(System.Object sender, System.EventArgs e)
- {
- create_button();
- }
Add new comment
- 78 views