Dynamically add a usercontrol in VB.net

非 Y 不嫁゛ 提交于 2020-01-01 11:52:50

问题


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

How can I add this dynamically to a form?


回答1:


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.




回答2:


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?




回答3:


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

Dim newControl As UserControl = LoadControl("~/Controls/DRQ/Create/UCNewControl.ascx")
Me.panelHolder1.Controls.Add(newControl)



回答4:


    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



回答5:


This is a method for adding two or more:

Private _userControlList As New List(Of YourControl)

Private Sub AddingControlOnPanel()
    Dim index As Integer = _userControlList.Count + 1
    Dim userControl As New YourControl
    userControl.Location = New System.Drawing.Point(SomeLocation)
    userControl.Size = New System.Drawing.Size(SomeSize)
    userControl.Name = "userControl" + index.ToString
    userControl.Visible = False
    _userControlList.Add(userControl)
    UserControlsPanel.Controls.Add(userControl)
    userControl.Visible = True
End Sub


来源:https://stackoverflow.com/questions/374082/dynamically-add-a-usercontrol-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!