How to create Dynamic Controls in VB.Net.


In this article I am going to show you how you can create Dynamic Controls like Text boxes, Buttons, Labels etc in Microsoft Visual Basic.Net.First create three buttons on a form and change their text property to Create Button, Create Text box and Create Labels and write the code as mentioned on the click events of these buttons.

In order to create Dynamic Controls like Text boxes, Buttons, Labels etc in Microsoft Visual Basic.Net. First start a new project and create a form and add 3 text boxes and change the text of the Buttons as Create Button, Create Textbox and Create Labels as shown in the image.
Now, add the following code in the code window of the form.


Public Class Form1
Dim x As Integer = 1
Dim y As Integer = 1
Dim z As Integer = 1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim button As New System.Windows.Forms.Button()
Me.Controls.Add(button)
button.Top = x * 30
button.Left = 100
button.Text = "Button " & Me.x.ToString
x = x + 1
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Txtbox As New System.Windows.Forms.TextBox()
Me.Controls.Add(Txtbox)
Txtbox.Top = y * 30
Txtbox.Left = 200
Txtbox.Text = "TextBox " & Me.y.ToString
y = y + 1
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim Label As New System.Windows.Forms.Label()
Me.Controls.Add(Label)
Label.Top = z * 30
Label.Left = 320
Label.Text = "Label " & Me.z.ToString
z = z + 1
End Sub

End Class


Finally run the project by pressing F5 and click on the buttons to start creating new buttons, Text Boxes and Labels on the form.

Regards


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: