繁体   English   中英

C#检查文本框中的整数

[英]c# check for integers in a textbox

我正在尝试检查文本框是否包含数字。 问题是它总是返回它包含一个非数字字符。 我尝试了几种方法,但似乎都没有用。

我尝试过的方法之一是:

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

我在文本框中输入的内容都没有关系,它总是返回它包含一个非数字字符(我尝试输入1-9,'a','b')

您可以将字符串解析为特定的数字类型,即

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

从您的正则表达式看来,您只需要整数值,因此应改用int.TryParselong.TryParse


快速而肮脏的测试程序:

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");
  }
}

结果:

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

您可以为此替换正则Regex

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

或为此:

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

您可以使用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