Sometimes you need to store control-state
data in order for a control to work properly. For example, if you have written
a custom control that has different tabs that show different information, in
order for that control to work as expected, the control needs to know which tab
is selected between round trips.
The View State property can be used for this purpose,
but view state can be turned off at a page level by developers, effectively
breaking your control. To solve this, the ASP.NET page framework exposes a
feature in ASP.NET called control state.
The Control State property allows you to persist
property information that is specific to a control and cannot be turned off
like the View State property.
Control state implementation:
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.
public class ControlStateWebControl
: Control
{
#region
Members
private string _strStateToSave;
#endregion
#region
Methods
protected override void OnInit(EventArgs
e)
{
Page.RegisterRequiresControlState(this);
base.OnInit(e);
}
}
protected override object SaveControlState()
{
return _strStateToSave;
}
protected override void LoadControlState(object state)
protected override void LoadControlState(object state)
{
if (state
!= null)
{
strStateToSave
= state.ToString();
}
}
#endregion
}
You
need to remember only one thing – the control state takes away the choice to
disable View State. You should only use it whenever you have to keep state information that without it
your control won’t work.
No comments:
Post a Comment