简体   繁体   中英

c# check for integers in a textbox

I am trying to check if a textbox contains a number. The problem is that it always returns that it contains a non-numeric character. I've tried several ways, but none of them seems to work.

One of the ways I've tried is:

if( Regex.IsMatch(tb.Text.Trim(), @"^[0-9]+$")) // tb.Text is the textbox 

It does not matter what I enter in the textbox, it always returns that it contains a non-numeric character (I tried entering 1-9, 'a', 'b')

You could just parse the string to a specific number type, ie

double result;
if (!double.TryParse(tb.Text, out result))
{
  //text is not a valid double;
  throw new Exception("not a valid number");
}
//else the value is within the result variable

From your regex it seems that you need only integer values, so you should use int.TryParse or long.TryParse instead.


Quick and dirty test program:

void Main()
{
    TestParse("1");
    TestParse("a");
    TestParse("1234");
    TestParse("1a");
}

void TestParse(string text)
{
  int result;
  if (int.TryParse(text, out result))
  {
    Console.WriteLine(text + " is a number");
  }
  else
  {
    Console.WriteLine(text + " is not a number");
  }
}

Results:

1 is a number 
a is not a number  
1234 is a number  
1a is not a number

You could replace your Regex for this:

if(Regex.IsMatch(tb.Text.Trim(), @"[0-9]"))

Or for this:

if(Regex.IsMatch(tb.Text.Trim(), @"\d"))

you can use TryParse:

int value;

bool IsNumber = int.TryParse(tb.Text.Trim(), out value);

if(IsNumber)
{
    //its number
}
private void btnMove_Click(object sender, EventArgs e)
        {
            string check = txtCheck.Text;
            string status = "";
            for (int i = 0; i < check.Length; i++)
            {
                if (IsNumber(check[i]))
                status+="The char at "+i+" is a number\n";
            }
            MessageBox.Show(status);
        }
        private bool IsNumber(char c)
        {
            return Char.IsNumber(c);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM