如何阻止刷新值?

时间:2014-03-27 21:02:51

标签: c#

我是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();
        }
    }
}
}

3 个答案:

答案 0 :(得分: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!");

答案 1 :(得分:3)

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

您总是从dBalance中减去总是500的内容。您应该做的是将新值保存在dBalance中:

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

理想情况下,不要在那里进行减法,而是创建一个名为doWithdraw()的方法,然后在那里进行计算。您需要添加支票以确保余额不会消极(除非您允许透支)等。

答案 2 :(得分:0)

您无法在任何地方更新dBalance。您只更新了txtBalance,但每次执行撤销调用时,您都会再次根据dBalance计算新值。