Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do nothing if textbox is empty (TextChanged Event) c#

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading