I have made a custom UserControl i Vb.net (windows application).
How can I add this dynamically to a form?
-
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?
-
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:
- Create a new instance of your control. Like
Dim X As New MyControl()
- 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. - Set the controls position within the container. That would be setting
X.Location
andX.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. - Create a new instance of your control. Like
-
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
Vilx- : Windows forms, people! :) -
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
0 comments:
Post a Comment