Adding Button Programmatically Using C#
In this tutorial I will teach you how to add a Button programmatically in C#.Net. With this method, there’s no need for you to drag and drop a Button in the Form anymore because the button will automatically appear on the Form . New Buttons will be added in the Form when clicked.
So, let’s get stated:
Open Microsoft Visual Studio and create a new Windows Form Application for C#. The Form will look like this.
After creating a Windows Form Application, go to the solution explorer and click the “code view“.
In the code view, declare the variables for counting the controls that will be added and setting up the location of the controls in the Form.
//SET A CLASS VARIABLE TO BE USED DURING THE FORM int Count_control = 0; Point Location_control = new Point(10,50);
After declaring variables, create a method for creating.
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 = 230; Location_control.Y += new_Button.Height + 10; //'CREATE THE EVENT HANDLER //AddingNewEventHandler new_Button.Click, myButtonHandler_Click; new_Button.Click += new EventHandler(myButtonHandler_Click); //'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.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { 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 method for adding another button when clicked.
public void myButtonHandler_Click(Object sender , EventArgs e ) { //'VERIFYING THE BUTTONS if(sender is Button) { create_button();//'CREATE A NEW BUTTON } }
Lastly, do this following codes for displaying the button on the first load of the form.
private void Form1_Load(object sender, EventArgs e) { create_button(); }
Output:
For all students who need programmer for your thesis system or anyone who needs a sourcecode in any programming languages. You can contact me @ :
Email – [email protected]
Mobile No. – 09305235027 – tnt