The Easiest Way to Create a Textbox Programmatically in C#

In this tutorial, I will teach you how to create a textbox programmatically in c#. This method has the ability to add an object in the form by clicking a button. It is also demonstrating how to get the collection of Controls within the control. Let's begin.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Do the form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, declare private variables for the location and count control.
  1.  
  2. private int count_control = 0;
  3. private Point location_control = new Point(10, 50);

Step 4

Create a method for creating a textbox.
  1.  
  2. private void createTexbox()
  3. {
  4. // 'INCREMENT THE COUNT_CONTROL.
  5. count_control += 1;
  6. //'CHECKING IF THE TEXTBOX HAS REACHED TO 6 OR NOT
  7. if (count_control <= 6)
  8. {
  9. // initialize a new object
  10. TextBox txt_new = new TextBox();
  11. //set a object properties
  12. txt_new.Name = "txt " + count_control.ToString();
  13. txt_new.Text = "textbox " + count_control.ToString();
  14. txt_new.Location = new Point(location_control.X + 10, location_control.Y);
  15. txt_new.Width = 350;
  16. location_control.Y += txt_new.Height + 10;
  17. // create a textbox
  18. Controls.Add(txt_new);
  19. }else
  20. {
  21. DialogResult result = MessageBox.Show("You've reached 6 controls. Do you want to clear controls to start again?", "Proceed", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
  22. if(result==DialogResult.OK)
  23. {
  24. //clear the controls
  25. Controls.Clear();
  26. //control return to 0
  27. count_control = 0;
  28. // set a new point for controls
  29. location_control = new Point(10, 50);
  30. //create a new textbox
  31. createTexbox();
  32. // add button again
  33. Controls.Add(button1);
  34. }
  35. }
  36.  
  37. }s

Step 5

Call the method that you have created in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. createTexbox();
  5. }
  6.  
Step 6 Write the following code for creating a textbox when the button is clicked.
  1.  
  2. private void button1_Click(object sender, EventArgs e)
  3. {
  4. createTexbox();
  5. }
For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below

Add new comment