簡體   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