简体   繁体   English

C#Winform文本框验证错误

[英]C# Winform Textbox Validation Error

I have 4 textboxes : 我有4个textboxes

  1. amount to pay 支付数量
  2. money (Verify the money of the customer) 钱(验证客户的钱)
  3. change (if money is greater than amount) 零钱(如果钱大于金额)
  4. and balance (if money is less than amount) 和余额(如果钱少于金额)

The last textbox is for the input (gets/inputs the money of the customer). 最后一个textbox用于输入(获取/输入客户的钱)。

I have placed my code into the TextChanged handler of textBoxInput (I'm thinking that every time the user inputs something on that textbox it will be automatically updated): 我已将代码放入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();
    }
}

It runs correctly, however whenever I press backspace (or clear the data) in the textbox , I get a format error. 它可以正常运行,但是每当我在textbox按退格键(或清除数据)时,都会出现格式错误。 I also get an error when I put a letter in it. 当我在其中放一个字母时,也会出现错误。 How can I prevent it make a will appear if the user inputs a letter and when the data is cleared? 如果用户输入字母并清除数据,如何防止出现遗嘱? Also, another error appears when I put a bigger value for ex. 另外,当我为ex设置更大的值时,还会出现另一个错误。

The amount to pay = 600, I input = 1000, the balance textbox has = 550, the change textbox has = 330. It doesn't compute correctly. 付款金额= 600,我输入= 1000,余额文本框= 550,更改文本框=330。计算不正确。 Can somebody help me with this? 有人可以帮我吗?

When dealing with money, it's usually better to use the Decimal type instead of Integer , but for your example, it's probably better to use the TryParse() method instead of the Parse . 处理金钱时,通常最好使用Decimal类型而不是Integer ,但对于您的示例,最好使用TryParse()方法代替Parse The format error happens because when you backspace, the textbox is empty and the parse fails. 发生格式错误的原因是,当您退格时,文本框为空,并且解析失败。

Quick rework: 快速返工:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM