在Textbox的輸入中﹐我們常常需要控制輸入的類型﹐比如說只能輸入數字﹐當然實現的方法很多﹐我總結了一下我做過的一些項目﹐我常會使用以下這三種﹕
 1﹑使用Try...Catch
 
        private static bool IsNumeric(string itemValue,int intFLag)
 
        
{
 
            try
 
            
{
 
                int i = Convert.ToInt32(itemValue);
 
                return true;
 
             }
 
            catch
 
            
{
 
                return false;
 
             }
 
         }
 2﹑使用正則表達式
 
using System.Text.RegularExpressions;
 
        
 
         private static bool IsNumeric(string itemValue)
 
        
{
 
            return (IsRegEx("^(-?[0-9]×[.]×[0-9]{0,3})$", itemValue));
 
         }
 
 
        private static bool IsRegEx(string regExValue, string itemValue)
 
        
{
 
            try
 
            
{
 
                 Regex regex = new System.Text.RegularExpressions.Regex(regExValue);
 
                if (regex.IsMatch(itemValue)) return true;
 
                else                          return false;
 
             }
 
            catch (Exception )
 
            
{
 
                return false;
 
             }
 
            finally
 
            
{
 
             }
 
         }
 
 3﹑判斷輸入的keyCode
 
        public static bool IsNumeric(System.Windows.Forms.KeyPressEventArgs e)
 
        
{
 
            if ((e.KeyChar  >= (char)48 && e.KeyChar<=(char)57) ||
 
                  e.KeyChar ==(char)8 || e.KeyChar ==(char)45 || e.KeyChar ==(char)47)
 
            
{
 
             }
 
            else
 
            
{
 
     e.Handled=true;  
 
             }
 
            return true;
 
         }
 public static bool isNumeric(string strInput)
     {
         char[] ca = strInput.ToCharArray();
         bool found = true;
         for (int i = 0; i < ca.Length; i++)
         {
             if ((ca[i] < '0' || ca[i] > '9') && ca[i] != '.')
             {
                 found = false;
                 break;
};
         };
         return found;
}
上一篇:从客户端中检测到有潜在危险的 Request.Form 值
下一篇:正则表达式判断
相关新闻
- 小程序登录流程图理解 2020-08-18
 - 在C#中获取web.config中的配置信息 2021-08-23
 - 小程序open-data头像样式 2021-04-10
 - 小程序rich-text 富文本解析图片过大和图片路径的问题 2020-11-25
 - C#中去掉字符串的最后一个字符 2020-11-23
 
                
                        
                    
