• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

How to persist child controls in custom control?

I am adding checkboxes to my custom control and expose them through properties. How can I persist these children controls? I get an error saying the CheckBox controls are not serializable so I cannot save them to the viewstate. My code that I am trying is below. How can I persist the checkboxes to the custom control- am I not exposing these child controls properly?
public class CustomControl : Control
{
public CheckBox Chk1
{
   get {
      if (ViewState["Chk1"] == null)
      {
         CheckBox control = new CheckBox();
         control.ID = "chk1";
         control.Text = "Test 1";
         ViewState["Chk1"] = control;
      }
 
      return ViewState["Chk1"] as CheckBox;
   }
   set { ViewState["Chk1"] = value; }
}
 
public CheckBox Chk2
{
   get {
      if (ViewState["Chk2"] == null)
      {
         CheckBox control = new CheckBox();
         control.ID = "chk2";
         control.Text = "Test 2";
         ViewState["Chk2"] = control;
      }
 
      return ViewState["Chk2"] as CheckBox;
   }
   set { ViewState["Chk2"] = value; }
}
...
protected override void CreateChildControls ()
{
   Controls.Add (this.Chk1);
   Controls.Add (this.Chk2);
 
   base.CreateChildControls();
}
}

Open in new window

0
bemara57
Asked:
bemara57
1 Solution
 
naspinskiCommented:
You can keep them in your session, I have an example here:
http://examples.naspinski.net/persist_dynamic.aspx

With the code here:
http://naspinski.net/post/Adding-Persistent--Controls-is-AspNet.aspx
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now