I’m dynamically loading User Controls into a div, which I need to preserve on postback in order to call a Save method once the user is done editing them. The div and all the User Controls have the EnableViewState = True.
ASPX Div Declaration
<div id="dynamicDiv" runat="server" enableviewstate="true">
</div>
Code Behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
'Implement some logic to load the User Controls using LoadControl
'Set all the userControl properties (including EnableViewState = True)
'Call a method in the user control to load it's content
Me.dynamicDiv.Controls.add(userControl)
End If
End Sub
Protected Sub Save(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
For Each t As userControlType In Me.dynamicDiv.Controls
t.Save()
Next
End Sub
So… the controls load fine, but I can’t find a way to preserver them on postback, I can’t reload them because the user has already input data into the usercontrol (which is what I need to save).
P.S. I tried adding them to a list and then adding the list to the ViewState, but I haven’t been able to properly serialize the control. I implemented ISerializable for the userControl’s code behind but then it says the ASCX is mot marked as serializable with
Type 'ASP.controls_userControlType_ascx' in Assembly 'App_Web_pn5vxhpw, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
Copied from comments:
You need to recreate your UserControls also if
IsPostback.You only need to assign the same IDs as before and add them in
Page_Loadat the latest. If you know the number of controls to create(which could be stored inViewState) you can derive the ID from the counter variable by appending it to the control-id.