creating usercontrols dynamically

roshanstevv

Member
Joined
Feb 8, 2007
Messages
12
Programming Experience
1-3
hi,
i have made a user control.i have to create this user control dynamically..
I have a textbox where i will enter how many user controls that I have to make..and I have to make that much usrcontrols in the webpage.
is there any way?


thks in advance,
 
VB.NET:
For i As Integer = 1 To 5
    Dim wuc As Control = LoadControl("~/WebUserControl.ascx")
    wuc.ID = "wuc" & i.ToString
    form1.Controls.Add(wuc)
Next
 
VB.NET:
For i As Integer = 1 To 5
    Dim wuc As Control = LoadControl("~/WebUserControl.ascx")
    wuc.ID = "wuc" & i.ToString
    form1.Controls.Add(wuc)
Next


Hi John

is LoadControl the only way to do this?

Is there any way to strongly type the user control so you can manipulate and assess the methods and variables? What about handling events?
 
Add reference to the control in directive:
HTML:
<%@ reference Control="~/wu.ascx" %>
This also allows to create new instance of this type and cast to it:
VB.NET:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim w As Wu = LoadControl("~/wu.ascx")
        w.ID = "someid"
        form1.Controls.Add(w)
        AddHandler w.evt, AddressOf wu_evt
    End Sub

    Protected Sub wu_evt()
        Me.Title = "usercontrol event happened"
    End Sub

    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim w As Wu = DirectCast(Page.FindControl("someid"), Wu)
        Me.Title = w.test
    End Sub
LoadControl method is needed for child controls of the user control to be created, as I have understood.
 
Back
Top