Simple way to check if a string is a correct integer?

  • Thread starter Thread starter Henke
  • Start date Start date
H

Henke

Hi!

Is there a simple way to check if a string entered in a text box is a valid
integer?

Thanks in advance!
/Henke
 
Use a regular expression to match the input with a pattern, say:

Match m=Regex.Match(inputString,"^[0-9]{1,}$";
if (m.Success) {
//whatever you want to do
}

The pattern above basically says:
[0-9] : check for the occurance of digits 0 to 9
{1,} : these can occur from 1 to infinite times
^ : there must be nothing in front of these digits
$ : there must be nothing behind these digits

success,
Paul
 
Henke said:
Is there a simple way to check if a string entered in a text box is a valid
integer?

The easiest thing to do is just parse it:

Convert.ToInt32(myString);

and catch the exception that you get if it's not valid.
 
Alternatively you could reference the VB.NET assembly located in the
references dialog and use the IsNumeric function available in VB.NET.
 
Thnaks for your answer, but on what object should I use IsNumeric? Is it a
static function on some VB data type?

/Henke

Peter Rilling said:
Alternatively you could reference the VB.NET assembly located in the
references dialog and use the IsNumeric function available in VB.NET.
 
Henke said:
Thnaks for your answer, but on what object should I use IsNumeric? Is it a
static function on some VB data type?

You'd call Microsoft.VisualBasic.Information.IsNumeric(string)

You'd also need to add a reference to the Microsoft.VisualBasic.dll
assembly.

Personally I'd steer clear of using the VB stuff - it makes your code
less portable (eg to Mono) and just feels a bit icky to me.
 
Hi!

Is there a simple way to check if a string entered in a text box is a valid
integer?

I just refused to accept anything but digits and backspace!

//
// OnKeyPress - only accept digits..
//
private void OnKeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = !(Char.IsDigit(e.KeyChar) || e.KeyChar == 8); // bksp
}
my email (e-mail address removed) is encrypted with ROT13 (www.rot13.org)
 
isNumeric sounds like it would have been a great method to be inside of
String. Can it be added?
 
Back
Top