How do I validate a textbox.text is integer?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi, I have a window based applicaton. I want to make sure that the users
enter integer numbers before I save it to the database. I know to code this
in the textbox_validating event but I don't know what function to call to
make sure the input are all integer nubmers.

Thanks, Alpha
 
I don't think there is a method (at least not in .NET 1.1). You can either
use a regular expression, or try to convert the string to an integer and
wrap it in a try...catch block.
 
One of the easiest ways would be to call a function like this from your event
handler that is handling the Validating event:

private bool IsInt(TextBox textbox)
{
try
{
int i = int.Parse(textBox1.Text);
return true;
}
catch
{
return false;
}
}

To call IsInt, you pass in a reference to the TextBox in question and it
attempts to parse the value in the Text property as an integer, if it
succeeds (ie doesn’t raise an exception), it returns true. If it fails
however (ie it was unable to parse it as an int), it will raise an exception
internally and return false.

There are other ways you could do this (ie not involving raising of
exceptions willy nilly), like making sure that the only numeric characters
are in the string, or using Regular Expressions... however as I said, this is
really the quickest and easiest way (code wise) to do it.

Brendan
 
Thank you very much.

Brendan Grant said:
One of the easiest ways would be to call a function like this from your event
handler that is handling the Validating event:

private bool IsInt(TextBox textbox)
{
try
{
int i = int.Parse(textBox1.Text);
return true;
}
catch
{
return false;
}
}

To call IsInt, you pass in a reference to the TextBox in question and it
attempts to parse the value in the Text property as an integer, if it
succeeds (ie doesn’t raise an exception), it returns true. If it fails
however (ie it was unable to parse it as an int), it will raise an exception
internally and return false.

There are other ways you could do this (ie not involving raising of
exceptions willy nilly), like making sure that the only numeric characters
are in the string, or using Regular Expressions... however as I said, this is
really the quickest and easiest way (code wise) to do it.

Brendan
 
Thank you.

Peter Rilling said:
I don't think there is a method (at least not in .NET 1.1). You can either
use a regular expression, or try to convert the string to an integer and
wrap it in a try...catch block.
 
Back
Top