Dynamically Add Text Box After Label

chalupabatman

Member
Joined
Jun 3, 2014
Messages
16
Programming Experience
Beginner
A more experienced user will probably laugh at the predicament I have gotten myself into but here goes. I am dynamically creating labels on a windows form flow layout panel. Perfect, formatting properly, lining up properly hooray! Well....now I need to dynamically create a text box that will dispaly directly after the aforementioned dynamically created labels. But with my flow layout panel it is creating the labels - then creating the text boxes so it lines up like so
VB.NET:
label1
label2
label3
label4
label5
textbox1
textbox2
textbox3
textbox4
textbox5

My desired output is
VB.NET:
label1  textbox1
label2  textbox2
label3  textbox3
label4  textbox4
label5  textbox5
 
Well no you don't need to create uc1 uc2 etc..., but you DO need to create a new instance of the user control.

Dim uc = New MyUserControl() With {.Name = "FirstUserControl"}
MyForm.Controls.Add(uc)

uc = New MyUserControl() With {.Name = "SecondUserControl"}
MyForm.Controls.Add(uc)

MyForm.FirstUserControl.Label.Text = "Some caption"
MyForm.SecondUserControl.TextBox.Text = "Some text"

I can't agree with that. When you design a user control, all the child controls really should be made Private. You then add properties to the user control itself to pass through the properties of the child controls that you need to access from the outside. In the case of a user control with a Label and a TextBox, you might do this:
Public Property LabelText() As String
    Get
        Return Me.Label1.Text
    End Get
    Set(value As String)
        Me.Label1.Text = value
    End Set
End Property

Public Property TextBoxText() As String
    Get
        Return Me.TextBox1.Text
    End Get
    Set(value As String)
        Me.TextBox1.Text = value
    End Set
End Property
You can now get and set the LabelText and TextBoxText properties of each user control as you would any other properties of any other control. Doing it this way is not necessary but it is good practice and now is the time to get into good habits.
 
Back
Top