Loading User Controls Dynamically
Hi,
I am trying to dynamically load a user control into a new row of an ASP.net table on the click event of a button. This works the first time I click the button but subsequent clicks of the button fail to add new rows.
I realise I need to re-add the rows that previously existed in the table, and from what I have read the best place to do this is the Page_Init because then the usercontrol should utilise its viewstate to pre-populate itself, but since the rows are added dynamically they don't exist within the Page_Init method when the button is clicked for a second time.
Does anyone know the best way to do this??
My code is this:
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
LoadFilters()
End Sub
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub
Private Sub btnAddFilter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddFilter.Click
AddFilter()
End Sub
Private Sub LoadFilters()
Dim row As TableRow
Dim i As Int32
Dim hidFilter As HtmlInputHidden
hidFilter = FindControl("hidFilterCount")
For i = 1 To Convert.ToInt32(hidFilter.Value)
AddFilter()
Next
End Sub
Private Sub AddFilter()
Dim trSearchFilter As New TableRow
Dim tdSearchFilter As New TableCell
Dim ucSearchFilter As New AdminSearchFilter
ucSearchFilter = LoadControl("~\UserControls\AdminSearchFilter.ascx ")
tdSearchFilter.Controls.Add(ucSearchFilter)
trSearchFilter.Cells.Add(tdSearchFilter)
tblSearchFilters.Rows.Add(trSearchFilter)
hidFilterCount.Value = Convert.ToInt32(hidFilterCount.Value) + 1
trSearchFilter.Dispose()
tdSearchFilter.Dispose()
End Sub
Regards,
Matt
|