i'm having one user control in asp.net ,i just want to add the user control multiple times in a single web page in 开发者_运维百科runtime in a separate table. How to do this?
thanks
Use the Page.LoadControl method to dynamically create a user control instance, and add it to a parent control like:
var uc = Page.LoadControl("~/uc.ascx");
this.Panel1.Controls.Add(uc);
Everytime the page posts back, you have to recreate the UC, fyi.
Dim tbl As New Table
Dim tr1 As New TableRow
tbl.Rows.Add(tr1)
Dim td1 As New TableCell
tr1.Cells.Add(td1)
Dim ctl As New CustomControl
ctl.Text = "Toto"
td1.Controls.Add(ctl)
It is some old code, which was working in .net 1.1 but it should still work.
So that you can reference each created control, you have to assign a unique id to each control:
Dim tempUserControl As UserControl
tempUserControl = Page.LoadControl("~/UserControl1.ascx")
tempUserControl.ID = "uniquename1"
testPanel.Controls.Add(tempUserControl)
tempUserControl = Page.LoadControl("~/UserControl1.ascx")
tempUserControl.ID = "uniquename2"
testPanel.Controls.Add(tempUserControl)
Then you can access the control on a later postback:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim tempUserControl As WebUserControl1
tempUserControl = testPanel.FindControl("uniquename1")
End Sub
精彩评论