views:

3357

answers:

4

I have made a custom UserControl i Vb.net (windows application).

How can I add this dynamically to a form?

+3  A: 

I think what you're looking for is written as: this.Controls.Add(myControl) in C#. I'm sure it's very similar in VB too?

Commander Keen
+3  A: 

A UserControl is essentially just another class. It inherits from Control, so you can do all kinds of things you do with controls, but otherwise it's just a class. Thus, to add the usercontrol dynamically to your form you'd do the following:

  1. Create a new instance of your control. Like Dim X As New MyControl()
  2. Add the control to your form as a child object to whatever container you want it. Like Me.MyGreatTabPage.Controls.Add(X). You can also add it directly to your form too, because a form is also a container.
  3. Set the controls position within the container. That would be setting X.Location and X.Size.

Remember that each instance you create with New MyControl() will be a separate MyControl. Don't make the mistake of repeatedly creating new controls and placing them over each other somehow. Create and place the control once. Assign it to a member variable to your form, and when you need to work with it, use this variable.

Vilx-
+1  A: 

Form.Controls.Add(Page.LoadControl("SomeUserControl.ascx"))

Then comes the hard part with trapping events in it since it needs to be reloaded every request. I normally use a ViewState flag to signify it's already loaded and the check for the existence of that flag to see if I sould reload it again in OnInit

Thomas Hansen
Windows forms, people! :)
Vilx-
A: 
    For i As Integer = 1 To 10
        Dim tb As New TextBox
        tb.Top = 26 * i
        tb.Left = 12
        tb.Text = "text box " & i.ToString()
        tb.Parent = Me
    Next
Christian Payne