如何判断文本输入的必须是数字才能有效呢
写一个明确的方法出来

解决方案 »

  1.   

    int n;
    string str="xxx";
    if(int.TryParse(str,out n))
    {
       //为数字
    }
    else
    {
     //非数字
    }
      

  2.   

    1、string pat=@"[\u4e00-\u9fa5]";
    Regex rg=new Regex(pat);
    Match mh=rg.Match(textBox1.Text);
    if(mh.Success)
    {
     //是汉字
    }
    2、function fucCheckNUM(NUM)
    {
    var i,j,strTemp;
    strTemp="0123456789.";
    if ( NUM.length== 0)
    return 0
    for (i=0;i<NUM.length;i++)
    {
    j=strTemp.indexOf(NUM.charAt(i)); 
    if (j==-1)
    {
    //说明有字符不是数字
    return 0;
    }
    }
    //说明是数字
    return 1;
    }
      

  3.   

    楼上正解。
    2003好像只有int.Parse()
    那就用try捕获一下异常
      

  4.   

    try
    {
      int.parse(输入的字符串);
    }
    catch(Exception e)
    {
       非数字……
    }
      

  5.   

    同意Zine_Alone(老鼠都给猫当伴娘了.哎.)int n;
    string str="xxx";
    if(int.TryParse(str,out n))
    {
    //为数字
    }
    else
    {
    //非数字
    }
      

  6.   

    你说的数字是全数字(123)还是123.00
    如果是第一种的话要用正则表达式或一个一个字符判断,但是如果是VS2005的话,可以设置textbox的checknum属性
    如果是后面的话,同意Zine_Alone(老鼠都给猫当伴娘了.哎.)
      

  7.   

    改为 Double.TryParse()即可。
      

  8.   

    void bool CheckNUM(string str)
    {
               if(str==string.Empty||string==null)
                 retrun false;
              try
                {
                    decimal.Parse(str)
                 }
            catch
              {
                 return false;  
              }
              return true;
    }
      

  9.   

    public static bool IsNumber(string strNumber)
    {
        Regex regex = new Regex("[^0-9]");
        return !regex.IsMatch(strNumber);

      

  10.   

    System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
              
    if(reg1.IsMatch(str))
    {
    //数字

    else
    {
    //非数字
    }
      

  11.   

    用RegularExpressions是最好的方法, 至于用int.Parse 或double.Parse都是有很大缺陷的,
     string s = "123456789012345678999999999999999999999999999999999999999999999999999999";
     文本s 都是数字,但你能用int.Parse吗?
      

  12.   

    劝你改用VB.net吧,不必为这些鸡毛蒜皮的小问题浪费太多的时间.
    VB.net有现成的函数IsNumber()If IsNumber("123.234") Then ...  'True
    If IsNumber("1a") Then ..        'False
    If IsNumber("$100") Then ...     'True
    If IsNumber("1.234E+10") Then .. 'True ...
      

  13.   

    用正则啊!!我用js实现的一个:
    function isNumber(str)
    {
      var patrn = /^[0-9]{1,20}$/;
      var num = patrn.test(str);
      if(!num)
      {
         alert("请输入数字!");
      }
    }
      

  14.   

    最简单的,使用TRY007网络安全小组 http://www.007spy.cn
      

  15.   

     static void Main(string[] args)
    {
    string aa="4578hhh2214";
    if(TsNum(aa))
    {
    System.Console.WriteLine("aaaaaa");
    }
    else
    {
    System.Console.WriteLine("bbbbbbb");
    }
    System.Console.ReadLine();
    } public static bool TsNum(string aa)
    {
    foreach(char st in aa)
    {
    if(!Char.IsNumber(st))
    {
    return false;
    }

    }
    return true;
    }
      

  16.   

    在文本框的OnTextChanged事件中写如下语句:string str = textBox1.Text; foreach( char c in str )
    {
    if( !char.IsNumber( c ) )
    {
    textBox1.Text = str.Replace( c.ToString(), string.Empty );
    textBox1.SelectionStart = textBox1.Text.Length;
    }
    }
      

  17.   

    .net 1.l里面,偶一般用try  catch  捕获int.parse的异常来判断
      

  18.   

    /// <summary>
    /// 判断是否为整数。是返回true 否返回false。可以传入null。
    /// </summary>
    /// <param name="strVal">要判断的字符</param>
    /// <returns></returns>
    public static  bool IsInt(string strVal)  
    {  
    if (strVal == null || strVal.Length == 0)
    return false;
    //判断是否只有.、-、 -.
    if (strVal == "." || strVal == "-" || strVal == "-.")
    return false; //去掉第一个负号,中间是不可以有负号的
    if (strVal.Substring(0,1) == "-")
    strVal = strVal.Remove(0,1); foreach(char c in strVal)
    {
    if (c < '0' || c > '9')
    return false;
    }
    return true;
    }
      

  19.   

    /// <summary>
    /// 判断是否是实数,是返回true 否返回false。可以传入null。
    /// </summary>
    /// <param name="strVal">要验证的字符串</param>
    /// <returns></returns>
    public static  bool IsNumeric(string strVal)  
    {  
    //System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex("-?([0]|([1-9]+\\d{0,}?))(.[\\d]+)?$");  
    //return reg1.IsMatch(strVal);  
    //string tmp="";
    //判断是否为null 和空字符串
    if (strVal == null || strVal.Length == 0)
    return false;
    //判断是否只有.、-、 -.
    if (strVal == "." || strVal == "-" || strVal == "-.")
    return false; //记录是否有多个小数点
    bool isPoint = false; //是否有小数点

    //去掉第一个负号,中间是不可以有负号的
    if (strVal.Substring(0,1) == "-")
    strVal = strVal.TrimStart('-'); foreach(char c in strVal)
    {
    if (c =='.')
    if (isPoint)
    return false;
    else
    isPoint = true;

    if ((c < '0' || c > '9') && c != '.')
    return false;
    }
    return true;
    }  效率最高的。
      

  20.   

    刚才那个IsNumeric还不算什么,哈
    判断日期,VB.net有现成的IsDate函数
    就像 "3/8/08","2/15/2002","2002 2 28","2月28日2002年","2月2002年28日","2002年2月28日,"2002-2-28","Oct 9 2008","2006/Feb/20" 这些格式,IsDate函数均可以将其转换成正确的日期并且加以判断。例:
    [VB.net]
      If IsDate("3/8/07") Then ....    ' True。函数将它识别为2007年3月8日
      If IsDate("2月2002年28日") Then. ' True。函数将它识别为2002年2月28日
      If IsDate("2/29/2001") Then ...  ' False。因为2001年的2月没有29日
      If IsDate("Oct-9-2008") Then...  ' True。函数将它识别为2008年10月9日可见这个函数的复杂性,不但涉及到区域文化问题,还设涉及到的长短格式等问题。
    这个功能如果用C#实现  肯定能把人累出屎来^-^.
      

  21.   

    楼上搞笑,导入Microsoft.VisualBasic.dll,C#可以直接用你说的那两个函数,在.net上讨论C#好还是VB.net好有意义?
      

  22.   

    class MyTest
        {
            public static void Main()
            {
                string temp;
                temp = Console.ReadLine();
                if (Microsoft.VisualBasic.Information.IsDate(temp))
                    Console.WriteLine("It's a date.");
                else Console.WriteLine("It isn't a date.");
                if (Microsoft.VisualBasic.Information.IsNumeric(temp))
                    Console.WriteLine("It's a number.");
                else Console.WriteLine("It isn't a number.");
            }
        }    如何导入dll就不用说了吧.....
      

  23.   

    double.tryParse()
    datatime.tryParse()
    .....
    .net2.0中新增加的东西,这个是最简单的转换方法,而且速度比较快。
      

  24.   

    正解:
    System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
              
    if(reg1.IsMatch(str))
    {
    //数字

    else
    {
    //非数字
    }
      

  25.   

    public static bool IsDigit(object obj)
        {
            if (null == obj) return false;        foreach (char ch in obj.ToString())
                if (!char.IsDigit(ch)) return false;        return true;
        }
      

  26.   

    用正则,\d+也可以,返回真是数字,返回假为未数字
          private bool NumbersCheck(string strNumbers)
            {
                Regex regex = new Regex("^[0-9]*$");
                bool blnCheck = regex.IsMatch(strNumbers);
                return blnCheck;  
            }
      

  27.   

    public static bool IsDigit(char c);
            //
            // 摘要:
            //     指示指定字符串中位于指定位置处的字符是否属于十进制数字类别。
            //
            // 参数:
            //   s:
            //     System.String。
            //
            //   index:
            //     s 中的字符位置。
            //
            // 返回结果:
            //     如果 s 中位于 index 处的字符是十进制数字,则为 true;否则,为 false。
            //
            // 异常:
            //   System.ArgumentOutOfRangeException:
            //     index 小于零或大于 s 中的最后一个位置。
            //
            //   System.ArgumentNullException:
            //     s 为 null。
            public static bool IsDigit(string s, int index);
      

  28.   

    1、KeyPress事件中加入如下代码即可:
    if(char.IsDigit(e.KeyChar))
    {
       e.Handled = false;
    }
    else
    {
       e.Handled = true;
    }或
    if(!char.IsDigit(e.KeyChar))
    {
       e.Handled = true;
    }
      

  29.   

    try 捕捉异常会浪费时间的
      

  30.   

    // 转化为int型
    public int ToInt(object data)
    {
    if( Regex.IsMatch( data.ToString(), @"^\-?\d{1,9}$" ) )
    {
    return Convert.ToInt32( data );
    }
    else
    {
    return 0;
    }
    }
    // 转化为double型
    public double ToDouble( object data )
    {
    if( Regex.IsMatch( data.ToString(), @"^\-?\d+[\.\d+]?$" ) )
    {
    return Convert.ToDouble( data );
    }
    else
    {
    return 0;
    }
    }
      

  31.   

    帮lz总结一下,条条大路通罗马,用什么方法要看环境,try 语句不适宜做这种用途,抛出异常是很浪费资源的1.Zine_Alone 说的方法,改用 decimal 类型,这种方法最快而且同时可解析出数值,可支持±1.0 × 10e&#8722;28 至 ±7.9 × 10e28,足够你用了,唯一缺点是不支持 Pre-.NET 2.0
    decimal result = 0;
    if(decimal.TryParse(s, out result))
    ......2.sealeft 说的方法,正则表达式,这种方法通用性强,但不如方法1
    if(System.Text.RegularExpressions.Regex.IsMatch(s, @"^[-]?\d+[.]?\d*$"))
    ......3.char.IsNumber or char.IsDigit,注意要加 '.' 号的判断,这种方法可支持任意长度字符串,效率未必差
    private bool IsNumeric(string s)
    {
                foreach (char c in s)
                {
                    if (c != '.' && !char.IsDigit(c))
                    {
                        return false;
                    }
                }
                return true;
    }4.用 VB 提供的方法,添加引用 Microsoft.VisualBasic,这种方法简单易用
    if(Microsoft.VisualBasic.Information.IsNumeric(s))
    ......
    日期的判断是类似的
    1.
    DateTime result = 0;
    if(DateTime.TryParse(s, out result))
    ......2.
    if(System.Text.RegularExpressions.Regex.IsMatch(s, @"^(\d{4})\-(\d{1,2})\-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$");)
    ......3.
    if(Microsoft.VisualBasic.Information.IsDate(s))
    ......btw: C# Coder 觉得 VB 有不错的方法尽管拿来用就是了,编译后都一样的,不必拘泥于门派之见,何况都是 .NET 一门,最多就是剑宗气宗罢了
      

  32.   

    int CheckNumber(const CString &number)
    {
        for (int i=0; i<number.GetLength(); i++) {
            if (( number[i]<'0') || (number[i]>'9')) {
                return -1;
             }
        }
        return 0;
    }
      

  33.   

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

  34.   

    在文本框的OnTextChanged事件中写如下语句:string str = textBox1.Text;foreach( char c in str )
    {
    if( !char.IsNumber( c ) )
    {
    textBox1.Text = str.Replace( c.ToString(), string.Empty );
    textBox1.SelectionStart = textBox1.Text.Length;
    }
    }方法太多了
      

  35.   

    这种帖也挂头条?
    用正则表达式使用Try不好,会导致时间很长        #region 校验字串是否是数字
            /// <summary>
            /// 校验字串是否是数字
            /// </summary>
            /// <param name="numberString"></param>
            /// <returns>bool</returns>
            public static bool IsNumeric(string numberString)
            {
                try
                {
                    Regex rCode = new Regex(@"^[-+]?\d+(\.\d+)?$");
                    if (!rCode.IsMatch(numberString))
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }        public int myfun(object x)
            {
                if (x == null || Convert.IsDBNull(x))
                {
                    return 0;
                }
                else
                {
                    switch (x.GetType().FullName)
                    {
                        case "System.String":
                            Regex rCode = new Regex(@"^-?\d+$");                        if (!rCode.IsMatch(x.ToString()))
                            {
                                return 0;
                            }
                            else
                            {
                                return int.Parse(x.ToString());
                            }
                        case "System.Int32":
                            return int.Parse(x.ToString());
                        default:
                            return 0;
                    }
                }
            }        #endregion
      

  36.   

    这个问题讨论的还挺热烈,个人认为,正则表达式才是好的解决办法,关于正则表达式判断是否为数字,有很多种,选择最适用于自己的就行;转换类型判断不可取,麻烦不说,异常的出现直接会影响效率。
    楼主的问题很宽,数字的范围还是很大的,整数、小数,小数位数都涉及到,这里给出一种方法,涉及到了数字长度、小数位数等:
    public static  bool VRegex(String value)
            {
                Regex reg = new Regex(@"^(([0])|([1-9]\d{0,23}))(\.\d{1,5})?$");
                if (reg.IsMatch(value))//reg.Match(value);
                    return true;
                return false;
            }
      

  37.   

    以下是我写的数字验证函数,请指教。
    /// <summary>
    /// 验证输入的数据是否为合法十进制数字
    /// </summary>
    /// <param name="str">需要验证的字符串</param>
    /// <param name="errorMessage">错误信息</param>
    /// <returns></returns>
    private static bool ValidDecmail(string str,out string errorMessage)
    {
    if (str.Length>0)
    {
    bool bol = false;  //为true时表示存在1个以上小数点 System.Text.ASCIIEncoding asc=new System.Text.ASCIIEncoding();
    byte[] arrbyte=asc.GetBytes(str); for (int j=0;j<arrbyte.Length;j++)
    {
    if (arrbyte[j]>57 || arrbyte[j]<48)
    {
    if (arrbyte[j]==46)
    {
    if (bol)
    {
    errorMessage = "格式错误!存在多个小数点!";
    return false;
    }
    else
    {
    bol = true;
    }
    }
    else
    {
    errorMessage = "格式错误!应输入十进制数字!";
    return false;
    }
    }
    } errorMessage="";
    return true; }
    else
    {
    errorMessage="";
    return true;
    }
    }
      

  38.   

    我没什么好说的,直接给出MS的做法吧。这个做法效率应该是最……的。public static bool IsNumeric(object Expression)
    {
        double result;
        IConvertible convertible = Expression as IConvertible;
        if (convertible == null)
        {
            char[] chArray = Expression as char[];
            if (chArray == null)
            {
                return false;
            }
            Expression = new string(chArray);
        }
        TypeCode typCode = convertible.GetTypeCode();
        if ((typCode != TypeCode.String) && (typCode != TypeCode.Char))
        {
            return IsOldNumericTypeCode(typCode);
        }
        string text = convertible.ToString(null);
        try
        {
            long num2;
            if (Utils.IsHexOrOctValue(text, ref num2))
            {
                return true;
            }
        }
        catch (StackOverflowException exception)
        {
            throw exception;
        }
        catch (OutOfMemoryException exception2)
        {
            throw exception2;
        }
        catch (ThreadAbortException exception3)
        {
            throw exception3;
        }
        catch (Exception)
        {
            return false;
        }
        return DoubleType.TryParse(text, ref result);
    }internal static bool IsOldNumericTypeCode(TypeCode TypCode)
    {
        switch (TypCode)
        {
            case TypeCode.Boolean:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.Single:
            case TypeCode.Double:
            case TypeCode.Decimal:
                return true;
        }
        return false;
    }
      

  39.   

    使用方法if(Microsoft.VisualBasic.Information.IsNumeric(str))
    {
    数字
    }
    else
    {
    非数字
    }所有异常由调用者处理才是最合适的。
      

  40.   

    强行转换 try catch 一下
      

  41.   

    如果是文本框,可以用keyPree事件,
    用e的属性,判断ASCII码
      

  42.   

    char.IsNumber(char c) 这个也很好用的
      

  43.   

    如果是文本框只让输入数字
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if(char.IsNumber(e.KeyChar))
    {
    e.Handled = false;
    }
    else 
    {        
    //其他的輸入則僅允許Backspace有作用   
    if( e.KeyChar != ((char)8) )      
    e.Handled = true; 
    }
    }
      

  44.   

    判断是否只含数字
    private bool isNum(string keyChar)
        {
            int i = 0;
            char c;
            for (i = 0; i < keyChar.Length; i++)
            {
                c = keyChar[i];
                if (!(c >= 48 && c <= 57))
                {
                    return false;
                }
            }
            return true;
        }判断是否只含小数点和数字
        private bool isDecimalNum(string keyChar)
        {
            int i = 0;
            char c;
            for (i = 0; i < keyChar.Length; i++)
            {
                c = keyChar[i];
                if (!(c >= 48 && c <= 57 || c == 46))
                {
                    return false;
                }
            }
            return true;
        }
    //判断是否只含数字
        private bool isNum(string str)
        {
            Regex r = new Regex("^[0-9]*$");
            Match m = r.Match(str);
            if (m.Success)
            {
                return true;
            }
            else 
            {
                return false;
            }
        }
    前两种方法可扩展性比较好,你对着ascii表想让输入哪个就加上它的ascii码就得了,后一种方法比较华丽,你学会后可以拿着去显摆一下
      

  45.   

    Regex regex = new Regex("^[0-9]*$");
                bool blnCheck = regex.IsMatch(strNumbers);
    正则,我也是这么用的
      

  46.   

    public static bool IsNumber(string strNumber)
    {
        Regex regex = new Regex("[^0-9]");
        return !regex.IsMatch(strNumber);
    }
      

  47.   

    if(!(Regex.IsMatch(TextBox2.Text,@"^[0-9]+(.[0-9]{1,2})?$")))
    {
      //不是带有两位小数的数字;
    }
      

  48.   

    /// <summary>
            /// 是否是小数 
            /// </summary>
            /// <param name="str">检测的对象</param>
            /// <returns></returns>
            public bool IsDouble(string str)
            {
                if (str == "+" || str == "-" || str == ".")
                {
                    return false;
                }
                if (str.Length > 1)
                {
                    if (str.IndexOf('+', 1) != -1)
                    {
                        return false;
                    }
                    if (str.IndexOf('-', 1) != -1)
                    {
                        return false;
                    }
                    if (str.IndexOf('.') != -1)
                    {
                        if (str.IndexOf('.', str.IndexOf('.') + 1) != -1)
                        {
                            return false;
                        }
                    }
                }
                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i] > '9' || str[i] < '0' && str[i] != '.' && str[i] != '+' && str[i] != '-')
                    {
                        return false;
                    }
                }
                return true;
            }
            /// <summary>
            /// 是否是整数
            /// </summary>
            /// <param name="str">检测的对象</param>
            /// <returns></returns>
            public bool IsInt(string str)
            {
                if (str == "+" || str == "-" || str == ".")
                {
                    return false;
                }
                if (str.Length > 1)
                {
                    if (str.IndexOf('+', 1) != -1)
                    {
                        return false;
                    }
                    if (str.IndexOf('-', 1) != -1)
                    {
                        return false;
                    }
                    if (str.IndexOf('.', 1) != -1)
                    {
                        return false;
                    }
                }
                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i] > '9' || str[i] < '0' && str[i] != '+' && str[i] != '-')
                    {
                        return false;
                    }
                }
                return true;
            }
            /// <summary>
            /// 是否是数字
            /// </summary>
            /// <param name="str">检测的对象</param>
            /// <returns></returns>
            public bool isNum(string str)
            {
                if (str == "+" || str == "-")
                {
                    return false;
                }
                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i] > '9' || str[i] < '0')
                    {
                        return false;
                    }
                }
                return true;
            }        /// <summary>
            /// (')字符转换('')
            /// </summary>
            /// <param name="str">转换的对象</param>
            /// <returns></returns>
            public string InputTrans(string str)
            {
                str = str.Replace("'", "''");
                return str;
            }
      

  49.   

    给你一个用jiavascript写的
           var d=c.match(/^(-|\+)?\d+$/);
           if(d==null)
            {
                alert("对不起,工作号必须是整数!!");
                return false;
            }
      

  50.   

    这有什么好争的啊,反编译微软的东西就是啊!
    public static bool IsNumeric(object Expression)
    {
          double num1;
          IConvertible convertible1 = Expression as IConvertible;
          if (convertible1 == null)
          {
                char[] chArray1 = Expression as char[];
                if (chArray1 != null)
                {
                      Expression = new string(chArray1);
                }
                else
                {
                      return false;
                }
          }
          TypeCode code1 = convertible1.GetTypeCode();
          if ((code1 != TypeCode.String) && (code1 != TypeCode.Char))
          {
                return Information.IsOldNumericTypeCode(code1);
          }
          string text1 = convertible1.ToString(null);
          try
          {
                long num2;
                if (Utils.IsHexOrOctValue(text1, ref num2))
                {
                      return true;
                }
          }
          catch (StackOverflowException exception1)
          {
                throw exception1;
          }
          catch (OutOfMemoryException exception2)
          {
                throw exception2;
          }
          catch (ThreadAbortException exception3)
          {
                throw exception3;
          }
          catch (Exception)
          {
                return false;
          }
          return DoubleType.TryParse(text1, ref num1);
    }
      

  51.   

    Public Shared Function IsNumeric(ByVal Expression As Object) As Boolean
          Dim num1 As Double
          Dim convertible1 As IConvertible = TryCast(Expression,IConvertible)
          If (convertible1 Is Nothing) Then
                Dim chArray1 As Char() = TryCast(Expression,Char())
                If (Not chArray1 Is Nothing) Then
                      Expression = New String(chArray1)
                Else
                      Return False
                End If
          End If
          Dim code1 As TypeCode = convertible1.GetTypeCode
          If ((code1 <> TypeCode.String) AndAlso (code1 <> TypeCode.Char)) Then
                Return Information.IsOldNumericTypeCode(code1)
          End If
          Dim text1 As String = convertible1.ToString(Nothing)
          Try 
                Dim num2 As Long
                If Utils.IsHexOrOctValue(text1, num2) Then
                      Return True
                End If
          Catch exception1 As  StackOverflowException
                Throw exception1
          Catch exception2 As  OutOfMemoryException
                Throw exception2
          Catch exception3 As  ThreadAbortException
                Throw exception3
          Catch exception7 As  Exception
                Return False
          End Try
          Return DoubleType.TryParse(text1, num1)
    End Function