只允许输入数字型Textbox演示

有一个需求,需要在GridView中批量输入数字!

 于是想到封装一个TextBox

代码如下:

None.gif public   class  NumberText : TextBox
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif        
private const string SMB_NUMBER_SCRIPT_ID = "{c4f7dcfd-8f9b-4fe8-8bd1-4a8a1f145c0c}";
InBlock.gif        
private const string SMB_NUMBER_SCRIPT_ONLY_HOOK = "return NumberEditor_KeyPress_Handle(this)";
InBlock.gif        
private const string SMB_NUMBER_SCRIPT_ONLY_SCRIPT = "<script language=\"javascript\">\n" +
InBlock.gif            
"function NumberEditor_KeyPress_Handle(ctrl)\n{{" +
InBlock.gif            
"if(event.keyCode == 13) \n return true;\n" +
InBlock.gif            
"if(event.keyCode<48 || event.keyCode>57 )\n" +
InBlock.gif            
"return false;\n else \n return true;\n}}" +
InBlock.gif            
"</script>";
InBlock.gif
InBlock.gif        
private void RenderJavscript()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (!Page.ClientScript.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), SMB_NUMBER_SCRIPT_ID, 
string.Format(SMB_NUMBER_SCRIPT_ONLY_SCRIPT, base.ID));
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void AddAttributesToRender(HtmlTextWriter writer)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
base.AddAttributesToRender(writer);
InBlock.gif            writer.AddAttribute(
"OnKeyPress", SMB_NUMBER_SCRIPT_ONLY_HOOK);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void OnPreRender(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
base.OnPreRender(e);
InBlock.gif            RenderJavscript();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public NumberText()
InBlock.gif            : 
base()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{ }
ExpandedBlockEnd.gif    }

关键点:第一,不要重复注册脚本,第二:要写在OnPreRender事件中

 在引用的Page页面中,可以这样调用 

None.gif   protected   override   void  OnPreLoad(EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
base.OnPreLoad(e);
InBlock.gif            NumberText number 
= new NumberText();
InBlock.gif            place1.Controls.Add(number);
//放在一个PlaceHolder中
ExpandedBlockEnd.gif
        }

这样一来, 这个 NumberText只接收数字输入,如果需要小数点,可以再修改代码。不过,这里建议用两个NumberText来拼一个浮点数字,这样很好验证,因为小数字的位置不好固定。当然用正则也可以。

这里给出另外一个例子,首先,客户端验证:

None.gif protected   void  Page_Load( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
if (!Page.ClientScript.IsClientScriptBlockRegistered("ClientCheck"))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), 
"ClientCheck", GetCheckScript());
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gifContractedSubBlock.gif            
if (txtAvePrice != nulldot.gif{ txtAvePrice.Attributes.Add("onblur""ClientCheckFunction('" + txtAvePrice.ClientID + "',6,2)"); }
ExpandedBlockEnd.gif        }

ExpandedBlockStart.gifContractedBlock.gif        
/**/ /// <summary>
InBlock.gif        
/// 得到一段检测输入是否为有效数据的脚本
InBlock.gif        
/// 使用方法:  txtBox..Attributes.Add("onBlur", "ClientCheckFunction('txtBox',6,2)");
InBlock.gif        
/// 说明检测的TextBox为 txtBox,并且整数位为6位,小数位为2位
InBlock.gif        
/// </summary>
ExpandedBlockEnd.gif        
/// <returns></returns>

None.gif          private   string  GetCheckScript()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
return @"<script language=""javascript"">
InBlock.gif                      function ClientCheckFunction(strid,nInt1,nInt2)
InBlock.gif                      {
InBlock.gif                        if(isNaN(document.getElementById((strid).value))
InBlock.gif                         {
InBlock.gif                              alert(""您输入的不是合法的数字。"");
InBlock.gif                              document.getElementById((strid).focus();
InBlock.gif                              document.getElementById((strid).select();
InBlock.gif                              return false;
InBlock.gif                         }
InBlock.gif                        var sm = '^(\\d){1,'+nInt1+'}$|^(\\d){1,'+nInt1+'}\\.(\\d){1,'+nInt2+'}$';
InBlock.gif                        var m = new RegExp(sm);
InBlock.gif                        if(!m.test(document.getElementById((strid).value))
InBlock.gif                         {
InBlock.gif                             alert('输入的数字整数位最多'+nInt1+'位,小数位最多'+nInt2+'位');
InBlock.gif                             document.getElementById((strid).focus();
InBlock.gif                             document.getElementById((strid).select();
InBlock.gif                             return false;
InBlock.gif                         }
InBlock.gif                        return true;
InBlock.gif                      }</script>
";
ExpandedBlockEnd.gif        }

第二步,服务器端验证:以GridView为例

前台页面:

None.gif   < asp:GridView  ID ="GVList"  runat ="server"  ShowFooter ="true"  AutoGenerateColumns ="False"
None.gif                BorderStyle
="Solid"  BorderColor ="#ffffff"  GridLines ="Horizontal"  CellSpacing ="1"
None.gif                Width
="640"  HorizontalAlign ="center"  BorderWidth ="0px"  EnableViewState ="true"
None.gif                DataKeyNames
="CustomID" >
None.gif                
< HeaderStyle  BackColor ="#1C5E55"  ForeColor ="White"  HorizontalAlign ="center"  Height ="30px"   />
None.gif                
< AlternatingRowStyle  BackColor ="#f7f7f7"   />
None.gif                
< RowStyle  HorizontalAlign ="center"  Height ="25px"  BackColor ="#E3EAEB"   />
None.gif                
< SelectedRowStyle  BackColor ="#C5BBAF"  Font-Bold ="True"  ForeColor ="#333333"   />
None.gif                
< Columns >
None.gif                    
< asp:TemplateField >
None.gif                        
< HeaderStyle  Width ="60px"  BackColor ="#1C5E55"  ForeColor ="White"   />
None.gif                        
< HeaderTemplate >
None.gif                            分类编号
</ HeaderTemplate >
None.gif                        
< ItemTemplate >
None.gif                            
< asp:Label  ID ="PKID"  Text ='<%#  DataBinder.Eval(Container.DataItem,"CustomID")% > '
None.gif                                runat="server" />
None.gif                        
</ ItemTemplate >
None.gif                    
</ asp:TemplateField >
None.gif                   
< asp:TemplateField >
None.gif                        
< HeaderStyle  Width ="60px"  BackColor ="#1C5E55"  ForeColor ="White"   />
None.gif                        
< HeaderTemplate >
None.gif                            单位
</ HeaderTemplate >
None.gif                        
< ItemTemplate >
None.gif                            
< asp:Label  ID ="C_Unit"  Text ="元/公斤"  runat ="server"   />
None.gif                        
</ ItemTemplate >
None.gif                    
</ asp:TemplateField >
None.gif                    
< asp:TemplateField >
None.gif                        
< HeaderTemplate >
None.gif                            最高价
</ HeaderTemplate >
None.gif                        
< ItemTemplate >
None.gif                            最高价:
None.gif                            
< asp:TextBox  ID ="txtMaxPrice"  runat ="Server"  CssClass ="PriceStyle"  MaxLength ="6"   />
None.gif                        
</ ItemTemplate >
None.gif                    
</ asp:TemplateField >
None.gif                    
< asp:TemplateField >
None.gif                        
< HeaderTemplate >
None.gif                            最低价
None.gif                        
</ HeaderTemplate >
None.gif                        
< ItemTemplate >
None.gif                            最低价:
< asp:TextBox  ID ="txtMinPrice"  runat ="Server"  CssClass ="PriceStyle"  MaxLength ="6"   />
None.gif                        
</ ItemTemplate >
None.gif                    
</ asp:TemplateField >
None.gif                    
< asp:TemplateField >
None.gif                        
< HeaderTemplate >
None.gif                            平均价
</ HeaderTemplate >
None.gif                        
< ItemTemplate >
None.gif                            平均价:
None.gif                            
< asp:TextBox  ID ="txtAvePrice"  runat ="Server"  CssClass ="PriceStyle"  MaxLength ="6"   />
None.gif                        
</ ItemTemplate >
None.gif                    
</ asp:TemplateField >
None.gif                
</ Columns >
None.gif            
</ asp:GridView >
None.gif  
< asp:Button  ID ="btnInsert"  Text ="上传所填数据"  runat ="server"  OnClientClick ="javascript:return confirm('每天只能上传一次,重复上传会替换今日已上传的数据,确认要上传您的报价信息吗?')"   />

后台代码:

None.gif private   void  btnInsert_Click( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
string str = CheckValid();
ExpandedSubBlockStart.gifContractedSubBlock.gif            
if (str.Trim().Length > 0dot.gifthis.Debug(str, this.ClientID); return; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
try dot.gif{ AddOneRecord(); }
InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif                
Loghandle by Tony 2008.11.21#region Loghandle by Tony 2008.11.21
InBlock.gif                
//string loginid = EmptyString;
InBlock.gif                
//myLogger.Error(GetErrorMessage(loginid, 1), ex);
InBlock.gif                
//Debug(ErrorHandle.GetErrorInfoByID(999), this.ClientID); return;
ExpandedSubBlockEnd.gif
                #endregion

ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif         }

None.gif       
private   string  CheckValid()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
string str = string.Empty;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
if (null == GVList) dot.gif{ str = "上传数据为空!"return str; }
InBlock.gif            
string strPre1 = ErrorHandle.GetErrorInfoByID(155);//获取错误信息
InBlock.gif
            string strPre2 = ErrorHandle.GetErrorInfoByID(156);//获取错误信息
InBlock.gif
            TestProj.Price.Framework.Components.Price2 p = new TestProj.Price.Framework.Components.Price2();
InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif            
Checkinput tony 2008.12.16#region Checkinput ////tony 2008.12.16
InBlock.gif            
foreach (GridViewRow gvr in GVList.Rows)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Label lb 
= (Label)(gvr.FindControl("PKID"));
InBlock.gif                
if (lb != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
int temp = SQLParser.IntParse(lb.Text);
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
if (temp > 0dot.gif{ p.P_Cate = "---编号[" + temp + "]"; }
ExpandedSubBlockEnd.gif                }

InBlock.gif                
//验证平均价
InBlock.gif
                TextBox tb = (TextBox)(gvr.FindControl("txtAvePrice"));
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (tb == null || tb.Text == EmptyString) dot.gif{ str = strPre1; return str + p.P_Cate; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
try dot.gif{ p.P_AverPrice = Double.Parse(tb.Text.Replace(dunhao, numberdot)); }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
catch dot.gif{ str = strPre2; return str + p.P_Cate; }
InBlock.gif                
//验证最低价
InBlock.gif
                tb = (TextBox)(gvr.FindControl("txtMinPrice"));
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (tb == null || tb.Text == EmptyString) dot.gif{ str = strPre1; return str + p.P_Cate; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
try dot.gif{ p.P_MinPrice = Double.Parse(tb.Text.Replace(dunhao, numberdot)); }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
catch dot.gif{ str = strPre2; return str + p.P_Cate; }
InBlock.gif                
//验证最高价
InBlock.gif
                tb = (TextBox)(gvr.FindControl("txtMaxPrice"));
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (tb == null || tb.Text == EmptyString) dot.gif{ str = strPre1; return str + p.P_Cate; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
try dot.gif{ p.P_MaxPrice = Double.Parse(tb.Text.Replace(dunhao, numberdot)); }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
catch dot.gif{ str = strPre2; return str + p.P_Cate; }
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (p.P_MinPrice > p.P_MaxPrice) dot.gif{ str = ErrorHandle.GetErrorInfoByID(157); return str + p.P_Cate; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (p.P_AverPrice < p.P_MinPrice) dot.gif{ str = ErrorHandle.GetErrorInfoByID(158); return str + p.P_Cate; }
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (p.P_AverPrice > p.P_MaxPrice) dot.gif{ str = ErrorHandle.GetErrorInfoByID(159); return str + p.P_Cate; }
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif            
#endregion

InBlock.gif            
return str;
ExpandedBlockEnd.gif        }

此时,每次验证结束时,将会提示用户一个编号,便于用户准确定位于错误行,以进行修改。

转载于:https://www.cnblogs.com/downmoon/archive/2008/12/18/1357561.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值