1

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?

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You Very Much Sir! I'm gonna have to research the difference between parse and tryparse :))
@rjtubera Here is the link to MSDN: Int32.TryParse Method
And i suggest to handle KeyPressEvent by not allowing Letter's on these TextBox-es just accept Decimal Number's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.