Monday, 10 December 2012

How to use control state Control State in asp.net

What is Control State?
The control state is a way to save a control’s state information when the EnableViewState property is turned off. Unlike ViewState a developer can’t turn off control state. The control state can be implemented only in controls that you implement.

How to Use Control State?

Control state implementation is easy. First, override the OnInit method of the control and add the call for the Page.RegisterRequiresControlState method with the instance of the control to register. Then, override the LoadControlState and SaveControlState in order to save the required state information.
The next example shows a simple implementation for a control that saves a string as a state information:
 
01.public class ControlStateWebControl : Control
02.{
03.#region Members
04.
05.private string _strStateToSave;
06.
07.#endregion
08.#region Methods
09.
10.protected override void OnInit(EventArgs e)
11.{
12. Page.RegisterRequiresControlState(this);
13. base.OnInit(e);
14.}
15.
16.protected override object SaveControlState()
17.{
18. return _strStateToSave;
19.}
20.
21.protected override void LoadControlState(object state)
22.{
23. if (state != null)
24. {
25. _strStateToSave = state.ToString();
26. }
27.}
28.
29.#endregion
30.}

You need to remember only one thing – the control state takes away the choice to disable ViewState. You should
only use it whenever you have to keep a state information that without it your control won’t work.

Summary

To sum up the post, I showed what is the control state and how to enable it in your controls. The control state takes away the decision of a developer whether to use ViewState or not. Whenever you want to use the control state you should think whether to implement it or give the decision of how to save the state information to the developers that use your control. I prefer the second choice. In the next post in this series I’ll start to explain the server side state
management.

 

 

Save multiple properties into Control State



To save multiple properties into Control State:
private int _prop1;
public int Prop1
{
get { return _prop1; }
set { _prop1 = value; }
}

private string _prop2;
public string Prop2
{
get { return _prop2; }
set { _prop2 = value; }
}

protected override object SaveControlState()
{
object[] state = new object[2]; // save the 2 properties
state[0] = _prop1;
state[1] = _prop2;

return state;
}

protected override void LoadControlState(object savedState)
{
object[] state = (object[])savedState;
_prop1 = (int)state[0];
_prop2 = (string)state[1];
}

No comments:

Post a Comment