It sounds like you're trying to do some numeric validation on the string. In this case, int.TryParse
is your friend - it takes an out
paramter that's set to the int
value of the string if it succeeds, and it returns false
if the string is not a valid int
.
Here's an example using your code above, although I changed the condition slightly. You were creating a cart_qty
variable and assigning it 0
, then adding that to the number the user entered, which doesn't do anything to change the number.
private void txtQty_TextChanged(object sender, EventArgs e)
{
int cart_qty;
// If TryParse returns true, then cart_qty will represent the value
if (int.TryParse(txtQty.Text, out cart_qty))
{
// Don't let them enter a negative number
if (cart_qty < 0)
{
MessageBox.Show("Unable to proceed. Quantity must be a positive number:",
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
// Don't let them enter a number larger than qty
else if (cart_qty > qty)
{
MessageBox.Show("Unable to proceed. Remaining quanity on hand is " + qty,
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
// cart_qty is valid, so do something here
}
}
// TryParse returned false, so the value was not a valid integer
else
{
MessageBox.Show("Unable to proceed. Must enter a valid integer.",
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}