使用以下代码,我试图计算一个运行总值。第一个文本框被禁用,并在执行计算后分配总计值。我也在跟踪所有以前的计算。
我的问题是:如何在每次计算后更新文本框中的数字?我无法想办法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Calculator
{
public partial class Calculator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int num1 = 0;
int num2 = int.Parse(TxtNum2.Text);
int total = 0;
string option = DropDownList1.SelectedValue;
if (option == "+")
{
total = num1 + num2;
lblResult.Text += num1 + " + " + num2 + " = " + total.ToString() + "<br/>";
num1 = total;
TxtNum1.Text = num1.ToString();
}
}
}
}
答案 0 :(得分:0)
您可以像这样使用UpdatePanel
:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
...
...
<asp:Button Text="Calculate" runat="server" ID="btnSubmit" />
<asp:UpdatePanel runat="server" id="up1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="Click"/>
</Triggers>
<ContentTemplate>
<asp:TextBox runat="server" ID="TxtNum1"/>
</ContentTemplate>
</asp:UpdatePanel>
这将异步更新TxtNum1
的值。如果您只想使用上次计算的结果,可以在btnSubmit_Click
方法的视图状态中保存/检索它。更好地做一个属性:
protected int Result
{
get
{
return (int)(ViewState["__result"] ?? 0);
}
set
{
ViewState["__result"] = value;
}
}
现在你可以像普通的字段变量一样使用它(忘记viewstate thingy)。
或者,如果你想要所有过去的结果,你将不得不使用另一种数据结构(List<T>
可能是?),只需在viewstate中添加/保存/检索。 / p>
答案 1 :(得分:0)
UpdatePanel
吗?如果没有,那么使用更新面板并将标签放在其中,以便它可以异步更新。