首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

验证输入的是否数字解决思路

2012-02-21 
验证输入的是否数字C#[解决办法]用正则表达式也可以static bool IsNumeric(string str){if (strnull ||

验证输入的是否数字
C#

[解决办法]
用正则表达式也可以
static bool IsNumeric(string str)
{
if (str==null || str.Length==0)
return false;
foreach(char c in str)
{
if (!Char.IsNumber(c))
{
return false;
}
}
return true;
}

正则表达的写法是:


static bool IsNumeric(string str)
{
System.Text.RegularExpressions.Regex reg1
= new System.Text.RegularExpressions.Regex(@ "^[-]?\d+[.]?\d*$ ");
return reg1.IsMatch(str);
}

[解决办法]
方法一:
try
{
orderid = System.Convert.ToInt32(Request.QueryString[ "orderid "].Trim());
//转换成功则继续执行。
}
catch (Exception ex)
{
//错误处理
}
方法二:
using System.Text.RegularExpressions;
string ex = "^[0-9]*$ ";
Regex reg = new Regex( ex,RegexOptions.IgnoreCase );
bool flag = reg.IsMatch( 要验证的string );


方法三:
public bool isNum()
{
string B=textBox1.Text;
try
{
double b=Convert.ToDouble(B);
return true;
}
catch(Exception)
{
return false;
}

}

方法四:
public bool IsNum(string s)
{
foreach(char c in textBox1.Text)
{
if(!Char.IsDigit(c))
return false;
}
return true;
}
//此方法中能判断为整型,不能判断浮点型。

热点排行