views:

456

answers:

4

I want to make custom control which has couple of <input type='checkbox' /> controls which I render in Render method. Is it possible to retain ViewState (e.g. checked or not) on these Controls?

There is a way of doing this by using ASP.NET server CheckBox control, adding them in OnLoad event with this.Controls.Add(), and giving them same Ids everytime, but I don't wat to do this :)

+1  A: 

You can just access the ViewState directly:

bool checked = (bool)(ViewState["ThisControlCheckState"] ?? false);
if (checked) {
    write("<input ... >");
}
else {
    write("<input ... >");
}

To save the value form the user, you could do something like this in the PostBack:

ViewState["ThisControlCheckState"] = request.Params["checkboxName"].ToString() == "1";
Frank Krueger
+2  A: 

If you want ViewState restored to a dynamic control, you must re-create that control before the load event. That means putting that code in the Init handler.

Joel Coehoorn
How should I recreate an HTML control before Load event?
ni5ni6
+2  A: 

When you create a control, make sure you add them to the page first, and set any properties on them afterwards. This because, in order for the ViewState manager to consider the control for management, it has to detect a change, and it can only detect changes after the control has been added to the Controls collection.

It is also important to set an explicit ID. When ViewState is saved and restored, the control IDs must match.

Also make sure that you create the controls in the right moment (OnInit) of the page lifecycle.

splattne
A: 

Frank, I like your answer, but what is the way to set the value of ViewState["ThisControlCheckState"] when the checkbox is checked?

ni5ni6
This kind of comment is best put in a comment to my original post. I will edit that post once I imagine the answer. :-)
Frank Krueger