W
Wei
Hi,
I have a simple custom button control which inherits from
the button web control. All it does is to display the
number of clicks. I am using the ViewState to record the
count, and I initially thought that the construstor will
only be executed once, so I initialized the ViewState
["Count"]=0 in it. The program runs fine. But when I debug
into the code, the thing suprises me is the constructor
gets called in each postback, which means the ViewState
["Count"] gets reset to 0 during each postback. But when
the value is fetched in the OnClick event, seems it gets
the value before it is reset which I cannot understand.
See code below.
I will appreciate anyone can figure out why.
Thanks,
Wei
public class CountedButton :
System.Web.UI.WebControls.Button
{
public CountedButton()
{// constructor is called in each postback
this.Text = "Click me";
ViewState["Count"] = 0;// it's reset to 0 each time
}
protected override void OnClick(EventArgs e)
{ // but why after the reset in constructor, the
View state keeps the original value(such as 2, 3,4) here???
ViewState["Count"]=((int)ViewState["Count"]) + 1;
this.Text = ViewState["Count"] + " clicks";
base.OnClick(e);
}
// count as property maintained in view state
public int Count
{
get{return (int) ViewState["Count"];}
set{ViewState["Count"] = value;}
}
}
I have a simple custom button control which inherits from
the button web control. All it does is to display the
number of clicks. I am using the ViewState to record the
count, and I initially thought that the construstor will
only be executed once, so I initialized the ViewState
["Count"]=0 in it. The program runs fine. But when I debug
into the code, the thing suprises me is the constructor
gets called in each postback, which means the ViewState
["Count"] gets reset to 0 during each postback. But when
the value is fetched in the OnClick event, seems it gets
the value before it is reset which I cannot understand.
See code below.
I will appreciate anyone can figure out why.
Thanks,
Wei
public class CountedButton :
System.Web.UI.WebControls.Button
{
public CountedButton()
{// constructor is called in each postback
this.Text = "Click me";
ViewState["Count"] = 0;// it's reset to 0 each time
}
protected override void OnClick(EventArgs e)
{ // but why after the reset in constructor, the
View state keeps the original value(such as 2, 3,4) here???
ViewState["Count"]=((int)ViewState["Count"]) + 1;
this.Text = ViewState["Count"] + " clicks";
base.OnClick(e);
}
// count as property maintained in view state
public int Count
{
get{return (int) ViewState["Count"];}
set{ViewState["Count"] = value;}
}
}