页面由两个Label和两个Button,还有一个页面类的private变量a。在点击Button1时,Label显示1,且给a赋1。在点击Button2时,Label2显示a的内容。
请问为什么此时a的内容为空,而Label1.Text内容依然为1?如果要在回送之后依然保持a的变量值,应该怎么办?
button 回送
------解决方案--------------------------------------------------------
变量被重置是因为你点击button的时候回发,重新执行一遍程序,变量又回到了初始值。
Label1的内容是靠ViewState来维护的,回发之后程序把ViewState中存储的控件值又恢复到控件了。
把Label1的ViewState禁用,你试试还会是1吗?
private string a;
protected void Page_Load(object sender, EventArgs e)
{
Label1.EnableViewState = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "1";
a = "1";
}
protected void Button2_Click(object sender, EventArgs e)
{
Label2.Text = a;
}
------解决方案--------------------------------------------------------
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["_a"]= (ViewState["_a"]==null?1:int.Pase(ViewState["_a"].ToString())) +1;
Label1.Text = ViewState["_a"].ToString();
}