在C#.Net中判斷輸入的字串是否是數字的方法

在Textbox的輸入中﹐我們常常需要控制輸入的類型﹐比如說只能輸入數字﹐當然實現的方法很多﹐我總結了一下我做過的一些項目﹐我常會使用以下這三種﹕
1﹑使用Try...Catch
None.gif          private   static   bool  IsNumeric( string  itemValue, int  intFLag)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
int i = Convert.ToInt32(itemValue);
InBlock.gif                
return true;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return false;
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }
2﹑使用正則表達式
None.gif using  System.Text.RegularExpressions;
None.gif        
None.gif         
private   static   bool  IsNumeric( string  itemValue) 
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
return (IsRegEx("^(-?[0-9]*[.]*[0-9]{0,3})$", itemValue));
ExpandedBlockEnd.gif        }
 
None.gif
None.gif        
private   static   bool  IsRegEx( string  regExValue,  string  itemValue) 
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Regex regex 
= new System.Text.RegularExpressions.Regex(regExValue);
InBlock.gif                
if (regex.IsMatch(itemValue)) return true;
InBlock.gif                
else                          return false;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return false;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

None.gif

3﹑判斷輸入的keyCode
None.gif          public   static   bool  IsNumeric(System.Windows.Forms.KeyPressEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
if ((e.KeyChar  >= (char)48 && e.KeyChar<=(char)57|| 
InBlock.gif                 e.KeyChar 
==(char)8 || e.KeyChar ==(char)45 || e.KeyChar ==(char)47)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif    e.Handled
=true;  
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return true;
ExpandedBlockEnd.gif        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值