How to create a TextBox Programmatically in Visual Basic 2008

In this turtorial, I will teach you how to create a TextBox programmatically by using Visual Basic 2008. With this, you don’t have to drag any TextBoxes in Form and set the location of it. It will create and set automatically. So let’s begin: First open Visual Basic 2008 and create a new Windows Form Application. After that, drag a button in the Form and it will look like this. FirstForm Go to the solution explorer and click the view code. SeconForm In the view code, declare the variable that will set the location of the TextBox and the number of it.
  1. 'SET A CLASS VARIABLE TO BE USED DURING THE FORM
  2. Private count_control As Integer = 0
  3. Private location_control As New Point(10, 50)
Create a sub routine for creating a TextBox.
  1. Private Sub create_textbox()
  2.  
  3. 'INCREMENT THE COUNT_CONTROL.
  4. count_control += 1
  5. 'CHECKING IF THE TEXTBOX HAS REACHED TO 5 OR NOT
  6. If count_control <= 5 Then
  7. 'SET A NEW TEXTBOX
  8. Dim new_textbox As New TextBox
  9. 'ADD THE PROPERTIES OF THE TEXTBOX.
  10. new_textbox.Name = "Textbox" + count_control.ToString()
  11. new_textbox.Text = "Textbox" + count_control.ToString()
  12. new_textbox.Location = New Point(location_control.X + 10, _
  13. location_control.Y)
  14. new_textbox.Width = 340 'SET THE WIDTH OF THE TEXTBOX
  15. location_control.Y += new_textbox.Height + 10 'ADDING A SPACE OF EVERY TEXTBOX
  16. 'ADD THE NEW TEXTBOX TO THE COLLECTION OF CONTROLS
  17. Controls.Add(new_textbox)
  18. Else
  19.  
  20. 'CHECKING IF YOU WANT TO CLEAR THE CONTROLS THAT YOU HAVE ADDED.
  21. If MessageBox.Show("You've reached 5 controls. Do you want to clear controls to start again?", _
  22. "Proceed", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) _
  23. = Windows.Forms.DialogResult.OK Then
  24. Controls.Clear() 'CLEARING THE CONTROL
  25. count_control = 0 'RETURNING THE COUNT_CONTROL TO ITS DEFAULT VALUE
  26. location_control = New Point(10, 50) 'SET A NEW POINT FOR THE CONTROLS
  27. create_textbox() 'PUT A CONTROL SO THAT YOU CAN ADD ANOTHER CONTROLS
  28. Controls.Add(Button1) 'ADD THE BUTTON1 AGAIN THAT YOU HAVE DRAG ON THE FORM.
  29. End If
  30. End If
  31. End Sub
Do this following code in the Form_Load.
  1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  2. 'CREATE A NEW TEXTBOX ON THE FIRST LOAD.
  3. create_textbox()
  4. End Sub
Finally, do this code for the click event handler of the Button.
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2. 'A NEW TEXTBOX WILL BE ADDED EVERYTIME YOU CLICK THE BUTTON
  3. create_textbox()
  4. End Sub

Add new comment