
Originally Posted by
pourkascheff
Consider you've created a control inside a form as follows:
Code:
Me.Controls.Add(New Label With {.Name = "Label1"})
How can I access it right after creation line accordingly?
Code:
Label1.Visible = True
Its not declaration error will be shown consequently.
How about declaring controls with similar names? Required argument accepts string after all and humans can make mistakes.
How about adding controls inside a TableLayoutPanel? Are the logic dictation applies here too?
Giving a control a name at runtime doesn't automatically create a variable of the same name. One way would be to create the variable explicitly and then add it to the collection e.g.
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim l1 As New Label With {
.Name = "Label1"
}
Me.Controls.Add(l1)
l1.Visible = True
End Sub
alternatively you could use the Find method on the Controls collection to locate the new Label and use that e.g.
Code:
Me.Controls.Add(New Label With {.Name = "Label1"})
Dim l1 As Label = DirectCast(Me.Controls.Find("Label1", True).First(), Label)
l1.Visible = True
another option would be to just set all the properties in one go when you create the control e.g.
Code:
Me.Controls.Add(New Label With {
.Name = "Label1",
.Visible = True
} )
obviously that isn't any good if you do need to do other things with the control.