2013-05-08 142 views
0

使用下面的代碼我試圖計算運行總值。第一個文本框被禁用,並在執行計算後分配總計值。我也跟蹤所有以前的計算。返回運行總計算器的值

我的問題是這樣的:如何在每次計算後更新文本框中的數字?我找不出一個辦法。

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

您應該對使用ViewBag(或ViewData)並將其變量包含在視圖中做一些研究。這是相當平凡的東西,你應該在教程中進行研究。 – doppelgreener 2013-05-08 00:46:49

+1

這個操作會更好留給客戶端的JavaScript。 – 2013-05-08 00:46:54

+1

@SpencerRuport:鑑於目前的稅收問題,擔心客戶端與服務器端可能會考慮太多。 – Guvante 2013-05-08 00:47:35

回答

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>可能?),只是添加/保存/檢索到/進入/從視圖狀態。

0

你可以顯示你的標記嗎?你有沒有用過UpdatePanel?如果不是,那麼使用更新面板,並在其中放置標籤,以便它可以異步更新。