2016-09-16 222 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,我们只是在字符串中有数字。
虽然这不能用小数点。

相关问题