简体   繁体   English

C#检查文本框中的整数

[英]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') 我在文本框中输入的内容都没有关系,它总是返回它包含一个非数字字符(我尝试输入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. 从您的正则表达式看来,您只需要整数值,因此应改用int.TryParselong.TryParse


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: 您可以为此替换正则Regex

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

Or for this: 或为此:

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

you can use TryParse: 您可以使用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);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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