In some book I’ve seen that they save custom properties of user control like this:
private int id = 0;
public int ID
{
get { return id; }
set { id = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
this.Page.RegisterRequiresControlState(this);
}
protected override void LoadControlState(object savedState)
{
object[] ctlState = (object[])savedState;
base.LoadControlState(ctlState[0]);
this.ID = (int)ctlState[1];
}
protected override object SaveControlState()
{
object[] ctlState = new object[2];
ctlState[0] = base.SaveControlState();
ctlState[1] = this.ID;
return ctlState;
}
My question is why can I simply store it (in setter) in viewstate like: Vistate[“ID”]=id;
and then retrieve it form there?
There is a difference between ViewState (what you are talking about in your question) and ControlState (what is shown in the sample code):
EnableViewState="false". In that case, you wouldn’t be able to restore your property’s value during the next request/postback (because there is no ViewState).See also these pages in MSDN: ASP.NET ViewState Overview and ControlState vs. ViewState
Excerpt from the first page: