tags:

views:

143

answers:

3

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!

A: 

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.

Robert
I think the OP is talking about WinForms, not WebForms.
Konrad Rudolph
+2  A: 

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.

Bill
+1  A: 

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
JaredPar