Link to home
Start Free TrialLog in
Avatar of BofADev
BofADev

asked on

How can I serialize an ASP.NET User Control?

I am programmatically adding user controls from an .ascx file into my application on Page_Load, which is necessary because the controls are populated with a database query and the query may return the need for any number of controls to be added.  I want to maintain these controls in the ViewState so that on post-back I can re-add the objects while maintaining the updated values from any changes a user might have made (selecting an item from a drop-down, for example).  When I try to add these controls to the ViewState, however, I get the following exception, which basically tells me that the Serializable attribute is not applied to my control's class:
System.Runtime.Serialization.SerializationException: Type 'ASP.MyClass' in Assembly 'App_Web_pf3y4e1h, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

If this were a standard vb class, then I would simply apply the <Serializable()> attribute just before the class declaration, but here the class declaration is implicit in the first line of the file:  
<%@ Control Language="VB" ClassName="MyClass" %>

I have accomplished my ultimate goal here before by manually creating a hashtable object with each of the properties of the control, and then manually re-adding the controls on post-back.  This, however, seems inefficient, since I already have an object to house this data.  How can I apply the Serializable attribute to my control?
ASKER CERTIFIED SOLUTION
Avatar of jnhorst
jnhorst

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BofADev
BofADev

ASKER

thanks for helping me think outside the box.  i typically try to avoid code-behinds, as they only make more files and more complexity.  however, this is a case when they're necessary, i suppose.
Try to use <Serializable()> for the class and for the properties:
<System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Content)>

Omar