Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
If you are curious, the difference between Parse and TryParse is best summed up like this:
The TryParse method is like the Parse
method, except the TryParse method
does not throw an exception if the
conversion fails. It eliminates the
need to use exception handling to test
for a FormatException in the event
that s is invalid and cannot be
successfully parsed. - MSDN
The TryParse statement returns a boolean representing whether the parse has succeeded or not. If it succeeded, the parsed value is stored into the second parameter.
//May be quite some time ago but I just want throw in some line for any one who may still need it
int intValue;
string strValue = "2021";
try
{
intValue = Convert.ToInt32(strValue);
}
catch
{
//Default Value if conversion fails OR return specified error
// Example
intValue = 2000;
}
Try this:
or better yet:
Also, since
Int32.TryParse
returns abool
you can use its return value to make decisions about the results of the parsing attempt:If you are curious, the difference between
Parse
andTryParse
is best summed up like this:The TryParse statement returns a boolean representing whether the parse has succeeded or not. If it succeeded, the parsed value is stored into the second parameter.
See Int32.TryParse Method (String, Int32) for more detailed information.
This would do
Or you can use
Refer Microsoft Developer Network for more information