【问题标题】:C# Windows forms - Assigning textBox value (numerical) from local variableC# Windows 窗体 - 从局部变量分配文本框值(数字)
【发布时间】:2014-01-07 13:55:50
【问题描述】:

此方法是减少 textBox1 的值,以减少插入到 textBox2 中的数量。如果 textBox1 中没有足够的“钱”,则应从 textBox3 中取出多余的金额。最后,方法应该将文本框更新为新值,但只有 textBox2 被清除,而 textBox1 和 textBox3 保持不变。谁能告诉我为什么textBox1.text = Account.toString() 没有将文本框值分配给变量Account 的值,而textBox3.text = Savings.toString() 没有将文本框值分配给变量Savings 的值?

public void Debit(decimal amount)
    {
        decimal Account = Convert.ToDecimal(textBox1.Text);
        decimal Savings = Convert.ToDecimal(textBox3.Text);

        if ((Account + Savings) < amount)
            if (Overdrawn != null)
                Owerdrawn(this, new OverdrawnEventArgs (Account, amount));
        else if (Account >= amount)
            Account -= amount;
        else {
            amount -= Account;
            Account = 0m;
            Savings -= amount;
        }
        textBox1.Text = Account.ToString();
        textBox2.Clear();
        textBox3.Text = Savings.ToString();
    }

【问题讨论】:

  • 你试过textBox1.Text = String.Format("N0", Account)吗?
  • 请养成描述性命名文本框的习惯。它将防止未来的程序员在查看您的代码时过早秃顶!
  • 谢谢!它就是这样工作的。但仍然无法弄清楚为什么使用 toString() 不起作用:/ @MichaelMcGriff 对不起,我会记住这一点

标签: c# .net winforms textbox


【解决方案1】:

您看到这些结果的唯一方法是遇到透支情况。如果 Account + Savings &lt; amount - 在这种情况下,您永远不会更改 AccountSavings 的值。

在其他所有情况下,您实际上都在更改这两个值,因此文本框的值也会更改。我很确定您想要该分支的代码是:

public void Debit(decimal amount)
{
    decimal Account = Convert.ToDecimal(textBox1.Text);
    decimal Savings = Convert.ToDecimal(textBox3.Text);

    if ((Account + Savings) < amount)
    {
        if (Overdrawn != null)
            Owerdrawn(this, new OverdrawnEventArgs (Account, amount));

        Account = (Account + Savings) - amount;
        Savings = 0m;
    }

    ...

    textBox1.Text = Account.ToString();
    textBox2.Clear();
    textBox3.Text = Savings.ToString();
}

【讨论】:

  • 如果 Account + Savings &lt; amount 文本框不应该被更改。在这种情况下,消息显示无法借记。其他两种情况都有问题。如果单击后 textBox1 中的 Account &gt;= amount 值没有减少,并且在第三种情况下 textBox1 和 textBox3 的值都没有减少。
  • @Marko,如果这是在引发此问题的事件期间唯一执行的代码 - 这不可能是问题所在。必须有另一种方法将值设置回来。您适当地减少了这些值。
猜你喜欢
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 2019-06-17
  • 2012-01-23
  • 2018-10-23
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多