You should use int.TryPrase()
instead of int.Prase()
.
int.Parse()
will throw an exception if the input string is not a valid integer, whereas int.TryPrase()
will return true/false
depending on whether the conversion is valid.
int.Parse()
This throws an exception.
string text = "abc";
int id = int.Parse(text);
but,
int.TryPrase()
This will return false
.
string text = "abc";
bool result = int.TryParse(text, out int value);
Edit
The reason why your program throws an exception is that the text in your TextBox
is not an integer value. The int.Parse()
method will convert a string value to int if it's a valid integer value. Therefore, if the TextBox
contains, for example, some characters like a
, b
etc, or even if it's an empty string, then the Parse()
method cannot convert it to an integer and thus throws an exception complaining that your input string is not in a correct format.
The int.TryParse()
method goes a step further. It tries to convert the value to an integer, and if successful, returns true
, and gives you the converted value in int format in the out
parameter. If it fails to convert because of a problem such as input string being in the wrong format, then it doesn't throw an exception. Instead it will return false
, and the out parameter will be set to zero
. This gives you the benefit of not having to catch an exception in the case of input being in the wrong format.
As Bradley pointed out, if you use int.TryParse()
you should always check the return value. If it's true
you know your conversion was successful. If it's false
you know something went wrong. So in case it's false
, before proceeding to next steps in your program you should do something about your input string not being a valid integer.