2016-09-16 120 views
-1

我需要檢查文本框中的輸入文本是數字還是字母,並根據條件執行一些操作。
我有一個項目列表顯示,用戶可以輸入序列號或字母表,基於排序應該完成。如何檢查文本框中輸入的文本是字母還是數字

string id = userTextBox1.Text; 
if (int.Parse(id) >= 0 && int.Parse(id) <= 9) 


{ 

//action to be performed 


} 

如何檢查輸入的文本是否字母表

+2

您的int.Parse將在無效輸入上失敗,請改爲使用int.TryParse。 –

+2

你是什麼意思的字母表?只有字母?只有「不可解析爲int」?順便說一句,如果你想避免異常,你應該使用'int.TryParse'... –

+3

'Regex.IsMatch(userTextBox1.Text,@「^ [a-zA-Z0-9] + $」);' –

回答

0

你可以(也應該)使用int.TryParse代替int.Parse的條件,否則,你得到一個異常,如果輸入的是無效的。那麼這應該工作:

int number; 
if(int.TryParse(userTextBox1.Text, out number)) 
{ 
    if(number >= 0 && number <= 9) 
    { 

    } 
    else 
    { 
     // invalid range? 
    } 
} 
else 
{ 
    // not an integer -> alphabet? (or what does it mean) 
} 

如果 「字母表」 僅指字母,沒有數字,你可以使用Char.IsLetter

// ... 
else if(userTextBox1.Text.All(char.IsLetter)) 
{ 
    // alphabet? 
} 
2

這應該工作:

using System.Linq; 
//...  

if (id.All(char.IsLetterOrDigit)) 
{ 
    //action to be performed 
} 
+2

我愛單行! –

0

我認爲你是尋找像這樣的東西:

protected void Validate_AlphanumericOrNumeric(object sender, EventArgs e) 
{ 
    System.Text.RegularExpressions.Regex numeric = new System.Text.RegularExpressions.Regex("^[0-9]+$"); 
    System.Text.RegularExpressions.Regex alphanemeric = new System.Text.RegularExpressions.Regex("^[a-zA-Z0-9]*$"); 
    System.Text.RegularExpressions.Regex alphabets = new System.Text.RegularExpressions.Regex("^[A-z]+$"); 
    string IsAlphaNumericOrNumeric = string.Empty; 
    if (numeric.IsMatch(txtText.Text)) 
    { 
     //do anything 
    } 
    else 
    { 
     if (alphabets.IsMatch(txtText.Text)) 
     { 
      //do anything 
     } 
     else if (alphanemeric.IsMatch(txtText.Text)) 
     { 
      //do anything 
     } 
    } 



} 

根據你的病情做你的工作

0
bool isNumber = id.Select(c => char.IsDigit(c)).Sum(x => x? 0:1) == 0; 

一種非常原始的方法,但它的作品。
我們根據值將文本轉換爲布爾列表並求和。如果它是0,我們只是在字符串中有數字。
雖然這不能用小數點。

相關問題