Reputation: 757
I have 4 textboxes
:
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?
Upvotes: 1
Views: 1187
Reputation: 81610
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();
}
Upvotes: 3