I've seen this problem a lot, and it's usually because the ViewState
variables are being evaluated too early in the page lifecycle, or that EnableViewState
is false, but I've checked for both of these and they are as I'd expect them to be.
My code:
public Int32 MyNumber
{
get
{
if (ViewState["MyNumber"] != null)
{
return (Int32)ViewState["MyNumber"];
}
return 0;
}
set
{
ViewState["MyNumber"] = value;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!this.IsPostBack)
{
MyNumber = 23;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
var numberValue = MyNumber;
}
When OnPreRender
is first called, numberValue
is 23. Every subsequent call thereafter it's 0. Every time there's a postback it appears to get reset.
Question
How do I get the value to persist after a postback?
What I've Tried
Bringing the value assignment outside of the check for a postback, but then that defeats the purpose of using ViewState
in the first place.
actually you have a missing order in your code block excaution and that makes the value reset by zero everytime between post packs :) ... in the onload Method you wrote the base.onload() method before your code block and that lead the Viewstate to be reset to 0 .
Please fellow that code correction:
Good Luck :).