简体   繁体   中英

C# Winform Textbox Validation Error

I have 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).

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):

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. 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.

The amount to pay = 600, I input = 1000, the balance textbox has = 550, the change textbox has = 330. It doesn't compute correctly. 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 . 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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