C#Winform文本框验证错误

时间:2012-01-23 00:18:37

标签: c# winforms validation textbox

我有4 textboxes

  1. 支付金额
  2. money(验证客户的钱)
  3. 更改(如果金额大于金额)
  4. 和余额(如果金额少于金额)
  5. 最后textbox用于输入(获取/输入客户的钱)。

    我已将我的代码放入textBoxInput的TextChanged处理程序中(我想每次用户在该文本框上输入内容时都会自动更新):

    private void textBoxInput_TextChanged(object sender, EventArgs e)
    {
        textBoxMoney.Text = textBoxInput.Text;
    
        if (int.Parse(textBoxAmount.Text) > int.Parse(textBoxMoney.Text))
        {
            int balance = int.Parse(textBoxAmount.Text) - int.Parse(textBoxMoney.Text);
            textBoxBalance.Text = balance.ToString();
        }
    
        if (int.Parse(textBoxMoney.Text) > int.Parse(textBoxAmount.Text))
        {
            int change = int.Parse(textBoxMoney.Text) - int.Parse(textBoxAmount.Text);
            textBoxChange.Text = change.ToString();
        }
    }
    

    它运行正常,但每当我按textbox中的退格键(或清除数据)时,我都会收到格式错误。当我写一封信时,我也会收到错误。如果用户输入一个字母并清除数据,如何防止它出现?此外,当我为ex。

    添加更大的值时,会出现另一个错误

    支付金额= 600,我输入= 1000,余额文本框= 550,更改文本框= 330.它无法正确计算。有人可以帮我吗?

1 个答案:

答案 0 :(得分:3)

在处理资金时,通常最好使用Decimal类型而不是Integer,但就您的示例而言,最好使用TryParse()方法而不是Parse方法1}}。发生格式错误的原因是当您退格时,文本框为空并且解析失败。

快速返工:

private void textBoxInput_TextChanged(object sender, EventArgs e) {
  textBoxMoney.Text = textBoxInput.Text;

  int amount = 0;
  int money = 0;
  int balance = 0;
  int change = 0;

  int.TryParse(textBoxAmount.Text, out amount);
  int.TryParse(textBoxMoney.Text, out money);

  if (amount > money)
    balance = amount - money;
  if (money > amount)
    change = money - amount;

  textBoxBalance.Text = balance.ToString();
  textBoxChange.Text = change.ToString();
}
相关问题