html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

C#验证输入的是否数字的几种方法_.NET教程_编程技术

[ ] 已经帮助:人解决问题

方法一:
  
   
     
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;
  }

    方法二:

private bool IsNumeric(string s)

private bool IsNumeric(string s)

         {

              char ch0 = '0';

              char ch9 = '9';

              for(int i=0; i < s.Length; i++)

              {

                  if ((s[i] < ch0 || s[i] > ch9))

                   {

                         this.lblwarning.Text="此处应输入整数且非负!";

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

    方法四:(可扩展)

public static bool IsConvert(string Expression,Type DataType)

{

  switch(DataType.Name)

  {

       case "Double":

              try

              {

                     Double.Parse(Expression);

                     return true;

              }

              catch

              {

                     return false;

              }

       case "DateTime":

              try

              {

                     DateTime.Parse(Expression);

                     return true;

              }

              catch

              {

                     return false;

              }

       default:

              return true;

  }

}

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

 

nKtHTML5中文学习网 - HTML5先行者学习网
nKtHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助