When I empty the textbox there is an error show that Input string was not in a correct format. This is the code.
private void txtQty_TextChanged(object sender, EventArgs e)
{
int cart_qty = 0;
if ((int.Parse(txtQty.Text) + cart_qty > qty))
{
MessageBox.Show("Unable to proceed. Remaining quanity on hand is " + qty, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
Now I want to try is to do nothing if the textbox is empty. How this works?
>Solution :
If txtQty.Text is "" then int.Parse(txtQty.Text) will produce an error, because "" can’t be translated into an integer value. The same would be true if the value is " " or "I'm not an integer" or any other non-integer text value.
Use int.TryParse instead, so you can handle the case when no valid integer is present:
int cart_qty = 0;
int parsedQty = 0;
if (int.TryParse(txtQty.Text, out parsedQty))
{
if (parsedQty + cart_qty > qty)
{
MessageBox.Show("Unable to proceed. Remaining quanity on hand is " + qty, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
else
{
// the input was not a valid integer
}
You could structure it in a variety of ways. Maybe if int.TryParse returns false then you just return; from the method immediately. Maybe you show a message to the user. Etc. But overall the point is to use TryParse instead of Parse if the value might not be a valid integer.