Page 1 of 1

C# Check if a user typed a number into a textbox.

Posted: Sun Apr 05, 2009 2:51 pm
by Keevu

Code: Select all

if(IsNumeric(textBox1.Text) == true)
  {
     // your convert code goes here
  }
  else
  {
     // your error message goes here
  }
put something like "please input number" where the your error message goes where comment is at.

snippet made by the great edward. I take no credit. :)

Re: C# Check if a user typed a number into a textbox.

Posted: Tue Apr 07, 2009 1:56 pm
by dandymcgee
Lol, wow. That was simple enough.

Re: C# Check if a user typed a number into a textbox.

Posted: Tue Apr 07, 2009 3:17 pm
by trufun202
Keevu wrote:

Code: Select all

if(IsNumeric(textBox1.Text) == true)
  {
     // your convert code goes here
  }
  else
  {
     // your error message goes here
  }
put something like "please input number" where the your error message goes where comment is at.

snippet made by the great edward. I take no credit. :)
actually..that's not correct. .NET doesn't have an IsNumeric() method built into the framework. That's an old VB method that didn't make it in the jump to .NET.

I would recommend the following:

Code: Select all

int number = 0;

if (int.TryParse(textBox1.Text, out number))
{
    //do something with number
}
else
{
    //scream at the user, cuz that's not a number!
}
EDIT: Or, a more user friendly option may be to use an asp:RegularExpressionValidator to validate the number on the client side.

Re: C# Check if a user typed a number into a textbox.

Posted: Mon Apr 27, 2009 10:19 am
by Keevu
trufun202 wrote:
Keevu wrote:

Code: Select all

if(IsNumeric(textBox1.Text) == true)
  {
     // your convert code goes here
  }
  else
  {
     // your error message goes here
  }
put something like "please input number" where the your error message goes where comment is at.

snippet made by the great edward. I take no credit. :)
actually..that's not correct. .NET doesn't have an IsNumeric() method built into the framework. That's an old VB method that didn't make it in the jump to .NET.

I would recommend the following:

Code: Select all

int number = 0;

if (int.TryParse(textBox1.Text, out number))
{
    //do something with number
}
else
{
    //scream at the user, cuz that's not a number!
}
EDIT: Or, a more user friendly option may be to use an asp:RegularExpressionValidator to validate the number on the client side.


thanks this helped it works very well. :)

Re: C# Check if a user typed a number into a textbox.

Posted: Fri Jul 31, 2009 6:09 am
by Apoc
Use decimal.TryParse unless you want to force non-floating-point numbers on the user. (In which case; I'd still use a larger datatype. long.TryParse for instance)

Also, don't use TryParse unless you're absolutely sure you want to suppress exceptions. (In simple cases like this, it's fine. In most other cases, avoid it wherever possible.)