Search code examples
vb.netwinformsaccess-modifiers

Setting modifiers for dynamically created controls


I have been creating some controls during runtime like below:

pnl1.Controls.Add(New TextBox() With _
{
    .Name = "ItemName", _
    .Anchor = AnchorStyles.Left + AnchorStyles.Right _
}

And I tried to set its modifier as Public. Unfortunately all of my attempts got failed.
My question is: Can we set modifers for dynamically created controls?

If not, then how could I access those controls in other forms? (Ex: Form1 having dynamically created control ctrl1, Form2 which is present inside of the MDI container of Form1).

How can I access ctrl1 from Form2? (without setting public modifier for ctrl1 in form1 we could not access it from Form2 like this me.parentform.ctrl1)


Solution

  • When not dinamically, the Visual Studio sets by default the controls as Friend With Events, in Vb.NET, declaring them before adding to the form. You can do the same, declare a Public List(Of Control) (for example) and adding your controls there when you create them dinamically.

    Or even better, a Dictionary(Of String, Control) to access the controls by its name.

    Or you can get them from the form. Using Form1.Controls you can access to all the controls in the form. If your control is inside another control, you need to reach the controls inside that control, for example:

    Dim btn As Label = Ctype(Form1.Controls("GroupBox1").Controls("Label1"), Label)