Creating a TextBox Programmatically in C#
In this turtorial, I will teach you how to create a TextBox programmatically by using C#.net. This topic explains a simple way on how to create a Textbox in the form. The TextBox will be displayed in the specified location according to your condition.
So, let’s begin:
Open Microsoft Visual Studio 2008 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 static int count_control = 0; static Point location_control= new Point(10, 50);
After declaring variables, create a method for creating a TextBox.
private void CreateATexBox() { //'INCREMENT THE COUNT_CONTROL. count_control += 1; //'CHECKING IF THE TEXTBOX HAS REACHED TO 5 OR NOT if( count_control <= 5 ){ //'SET A NEW TEXTBOX TextBox new_textbox = new TextBox(); //'ADD THE PROPERTIES OF THE TEXTBOX. new_textbox.Name = "Textbox" + count_control.ToString(); new_textbox.Text = "Textbox" + count_control.ToString(); new_textbox.Location = new Point(location_control.X + 10, location_control.Y); new_textbox.Width = 340; //'SET THE WIDTH OF THE TEXTBOX location_control.Y += new_textbox.Height + 10; //'ADDING A SPACE OF EVERY TEXTBOX // 'ADD THE NEW TEXTBOX TO THE COLLECTION OF CONTROLS Controls.Add(new_textbox); } 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) == 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 FOR THE CONTROLS CreateATexBox(); //'PUT A CONTROL SO THAT YOU CAN ADD ANOTHER CONTROLS Controls.Add(button1); //'ADD THE BUTTON1 AGAIN THAT YOU HAVE DRAG ON THE FORM. } } }
Go back to the design view, double click the button and do the following code for creating a TextBox in the Form.
private void button1_Click(object sender, EventArgs e) { //'A NEW TEXTBOX WILL BE ADDED EVERYTIME YOU CLICK THE BUTTON CreateATexBox(); }
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