Saturday, April 7, 2007

Difficulties With ViewState(Solve . . .)

Are you facing some difficulties with ViewState ?
ASP.NET 2.0 provide you a solution for managing ViewState
Which is called Control State

You just put your private variable in control state and write the code for which variable you want to save and load, ASP.NET will load and save them for you... Wow!

And to do that you have to override write the following code :

1. override void OnInit(EventArgs e)
2. override object SaveControlState()
3. override void LoadControlState(object state)

Typically "override void OnInit(EventArgs e)" method have the following code :

override void OnInit(EventArgs e)

{
Page.RegisterRequiresControlState(this);
base.OnInit(e);
}



And I suggest a data structure for the next two one:
Use a dictionary with Dictionary
use your variable name a key and your variable as object
Like the following code:

override object SaveControlState()
{
Pair newState = new Pair();
newState.First = base.SaveControlState();
Dictionary privateMemebrs = new Dictionary();
privateMemebrs["a"] = this.a;
privateMemebrs["b"] = this.b;
privateMemebrs["c"] = this.c;
newState.Second = privateMemebrs;
return newState;
}



protected override void LoadControlState(object state)
{
if (state == null)
return;

Pair newState = (Pair)state;
base.LoadControlState(newState.First);
if (newState.Second != null)
{
Dictionary privateMemebrs = (Dictionary)newState.Second;
this.a = (List)privateMemebrs["a"];
this.b = (int)privateMemebrs["b"];
this.c = (string)privateMemebrs["c"];
}
}

No comments:

Post a Comment

Please, no abusive word, no spam.