2014-03-27 38 views
1

我是C#的新手,試圖爲大學作業創建一個基本的模擬儲蓄賬戶界面,但是當我從500的餘額中扣除一定數額的金錢時,當我再次扣除時它會再次刷新。例如,如果我退出10,我將有490,那麼如果我撤回5,它將從500中拿走,我將再次拿到495。我如何保留這個價值? 下面是代碼:如何阻止刷新的價值?

namespace Savings_Account 
{ 
    public partial class Menu : Form 
    { 
     public Menu() 
     { 
      InitializeComponent(); 
      txtBalance.Text = Convert.ToString("£" + dBalance); 
      grpWithdraw.Enabled = false; 
     } 

     decimal dBalance = 500; 
     decimal dWithdraw; 

     private void txtPin_TextChanged(object sender, EventArgs e) 
     { 
      if (txtPin.Text == "1234") 
     { 
      grpWithdraw.Enabled = true; 
     } 
    } 

    private void btnWithdraw_Click(object sender, EventArgs e) 
    { 
     if (!decimal.TryParse(txtWithdraw.Text, out dWithdraw)) 
     { 
      txtWithdraw.Clear(); 
      MessageBox.Show("An invalid character has been entered"); 
     } 
     else 
     { 
      txtBalance.Text = "£" + (dBalance - dWithdraw).ToString(); 
      txtWithdraw.Clear(); 
     } 
    } 
} 
} 
+0

這是什麼平臺 - WinForms,ASP.NET? – n8wrl

+0

@ n8wrl:沒關係,是嗎? – xbonez

+0

請勿在標題中使用標籤... – rene

回答

5

使用變量dBalance

dBalance = dBalance - dWithdraw; 
    txtBalance.Text = "£" + dBalance.ToString(); 

這樣的變量dBalance將在每次退出更新自己算算。

也許是有點早擔心,但一個測試來檢查,如果你有足夠的錢應該是強制性的

if(dBalance - dWithdraw > 0) 
    { 
     dBalance = dBalance - dWithdraw; 
     txtBalance.Text = "£" + dBalance.ToString(); 
    } 
    else 
     MessageBox.Show("Not enough funds!"); 
3
txtBalance.Text = "£" + (dBalance - dWithdraw).ToString(); 

你總是減去dBalance這始終是500什麼你應該做的,而不是被保存在dBalance新值:

dBalance = dBalance - dWithdraw 
txtBalance.Text = "£" + dBalance.ToString(); 

理想的情況下,而不是做減法那裏,創造一種稱爲doWithdraw()什麼的,並在那裏做計算。您需要添加支票以確保餘額不會變爲負值(除非您允許過度編制)等。

0

您並未更新dBalance anyplace。您只更新txtBalance,但每次執行撤回呼叫時,都會再次基於dBalance計算新值。