2

I need to dynamically create textbox. This is my code, but with this I create only one textbox:

 Public Sub CreateTextBox()
        Dim I As Integer
        Dim niz As Array
        For I = 1 To 5
           Dim myTextBox = New TextBox
           myTextBox.Text = "Control Number:" & I
            Me.Controls.Add(myTextBox)
        Next

    End Sub

So how i can dynamically create textbox?

Thanks!

4
  • 8
    Are you sure they're not just all on top of each other? Commented Mar 20, 2010 at 16:30
  • What is niz used for? A declaration As Array is almost certainly an error in VB. Commented Mar 20, 2010 at 16:33
  • 1
    @Chris: make your comment an answer, you deserve the reputation, and the question can be marked as complete/answered. Commented Mar 20, 2010 at 16:39
  • Chris has it exactly right. You need to set top/left properties for the textboxes or else they'll be rendered on top of each other. Commented Mar 20, 2010 at 16:41

3 Answers 3

2

This code is actually creating 5 instances of TextBox and adding them to the current form. The problem is that you are adding them one on top of another. You need to use a layout mechanism to display them correctly.

For example this code will add them to a FlowLayoutPanel in a top down fashion.

Public Sub CreateTextBox()
  Dim I As Integer
  Dim panel as New FlowLayoutPanel()
  panel.FlowDirection = FlowDirection.TopDown
  For I = 1 To 5
    Dim myTextBox = New TextBox
    myTextBox.Text = "Control Number:" & I
    panel.Controls.Add(myTextBox)
  Next
  Me.Controls.Add(panel)

End Sub
Sign up to request clarification or add additional context in comments.

Comments

2

Chris is right. You didn't set the location so the control uses the default location for each one. They are stacked on top of each other.

You might also want to create a separate collection of the textboxes added so that you can access them separately from the Forms.Controls collection.

Also you may want to use the .Tag property to identify the created control in some way.

Comments

0

You need to set the ID property of the control to be unique for each control. Also remember that with dynamically created controls, you must recreate them with each page post in order to be able to retrieve any information from the controls collection.

1 Comment

I think the OP is talking about WinForms, not WebForms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.