[英]C#: Value not persisting in postback
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class expt2 : System.Web.UI.Page
{
double result ;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
result = 0.0;
protected void Chkbxbd_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxbd.Checked)
{
txtbxttl.Text = "" + 10000;
result += double.Parse(txtbxttl.Text);
}
else
result = result - 10000;
}
protected void Chkbxsfa_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxsfa.Checked)
{
txtbxttl.Text = "" + 15000;
result += double.Parse(txtbxttl.Text);
}
else
result = result - 15000;
}
protected void btnttl_Click(object sender, EventArgs e)
{
txtbxttl.Text = "" + result;
}
}
在此代碼中,復選框的各個值都可以,但是合計后為0。
請幫助我修復它。
“結果”值不會通過回發保留。 總是在需要最終結果時重新計算它,或將其存儲在viewstate中。
由於Web應用程序的本質是狀態較少的,因此result變量將不會被無數次回發,因此將結果撕裂到ViewState或Session變量中,如下所示。
public partial class expt2 : System.Web.UI.Page
{
double result ;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
Session["result"] = 0.0;
}
protected void Chkbxbd_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxbd.Checked)
{
txtbxttl.Text = "" + 10000;
result = double.Parse(Session["result"].ToString());
result += double.Parse(txtbxttl.Text);
Session["result"] = result;
}
else
{
result = double.Parse(Session["result"].ToString());
result = result - 10000;
Session["result"]= result;
}
}
protected void Chkbxsfa_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxsfa.Checked)
{
txtbxttl.Text = "" + 15000;
result = double.Parse(Session["result"].ToString());
result += double.Parse(txtbxttl.Text);
Session["result"] = result;
}
else
{
result = double.Parse(Session["result"].ToString());
result = result - 15000;
Session["result"] = result;
}
}
protected void btnttl_Click(object sender, EventArgs e)
{
txtbxttl.Text = "" + Session["result"].ToString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.