0

I have the following form:

enter image description here

My field Quantity should be an int but I want to implement error checking.

This is my code:

   private void btn_Create_Click(object sender, EventArgs e)
        {

            bool exit = false;

            if (String.IsNullOrEmpty(tb_Quantity.Text))
            {
                lbl_Error.Visible = true;
                lbl_Error.Text = "Check required values !";
                exit = true;
            }

            int Quantity = int.Parse(tb_Quantity.Text.Trim());


            if (!exit)
            {
                MessageBox.Show("Ready to be created!");
            }

        }

The error that I get if my quantity is empty:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

What am I doing wrong?

user3127554
  • 521
  • 1
  • 7
  • 28

1 Answers1

2

Instead use TryParse() like below which won't throw exception in-case the casting fails (if it's NaN)

int.TryParse(tb_Quantity.Text.Trim(), out int quantity);
Rahul
  • 76,197
  • 13
  • 71
  • 125