interviews.dotnetthread.com

↑ Grab this Headline Animator

Thursday, October 16, 2008

What is Control State and How to use Control State?

If you observe that even though we disable ViewState for TextBox control the state of the textbox is preserved i.e the text entered in textbox is preserved on page postbacks.

This uses Control State. It is a way to save controls state information when EnableViewState property is set to false for a control. We can use this whenever we feel that control wont work in desired manner without sate information. To maintain state information even though Enable ViewState is made false.

We can implement this for custom controls in the same way it is implimented for TextBox. To impliment Control State first we need to 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. Sample code is as shown below.

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)
{
if (state != null)
{
_strStateToSave = state.ToString();
}
}

#endregion
}

Submit this story to DotNetKicks

2 comments:

sandhya said...

can we use it for the storing username and password , as commonly we are using session for this.

Ani said...

sandhya:

ControlState will work like ViewState. i.e state will be maintained only for that page upon post backs.

It will not give sate in other pages like Sessions.

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles