有一个需求,需要在GridView中批量输入数字!
于是想到封装一个TextBox
代码如下:
<!--{cps..0}-->
publicclassNumberText:TextBox


{
privateconststringSMB_NUMBER_SCRIPT_ID="{c4f7dcfd-8f9b-4fe8-8bd1-4a8a1f145c0c}";
privateconststringSMB_NUMBER_SCRIPT_ONLY_HOOK="returnNumberEditor_KeyPress_Handle(this)";
privateconststringSMB_NUMBER_SCRIPT_ONLY_SCRIPT="<scriptlanguage=/"javascript/">/n"+
"functionNumberEditor_KeyPress_Handle(ctrl)/n{{"+
"if(event.keyCode==13)/nreturntrue;/n"+
"if(event.keyCode<48||event.keyCode>57)/n"+
"returnfalse;/nelse/nreturntrue;/n}}"+
"</script>";

privatevoidRenderJavscript()


{
if(!Page.ClientScript.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))


{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),SMB_NUMBER_SCRIPT_ID,string.Format(SMB_NUMBER_SCRIPT_ONLY_SCRIPT,base.ID));
}
}

protectedoverridevoidAddAttributesToRender(HtmlTextWriterwriter)


{
base.AddAttributesToRender(writer);
writer.AddAttribute("OnKeyPress",SMB_NUMBER_SCRIPT_ONLY_HOOK);
}

protectedoverridevoidOnPreRender(EventArgse)


{
base.OnPreRender(e);
RenderJavscript();
}

publicNumberText()
:base()


{}
}















































关键点:第一,不要重复注册脚本,第二:要写在OnPreRender事件中
在引用的Page页面中,可以这样调用
<!--{cps..1}-->
protectedoverridevoidOnPreLoad(EventArgse)


{
base.OnPreLoad(e);
NumberTextnumber=newNumberText();
place1.Controls.Add(number);//放在一个PlaceHolder中
}








这样一来, 这个 NumberText只接收数字输入,如果需要小数点,可以再修改代码。不过,这里建议用两个NumberText来拼一个浮点数字,这样很好验证,因为小数字的位置不好固定。当然用正则也可以。
这里给出另外一个例子,首先,客户端验证:
<!--{cps..2}-->
protectedvoidPage_Load(objectsender,EventArgse)


{
if(!Page.ClientScript.IsClientScriptBlockRegistered("ClientCheck"))


{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),"ClientCheck",GetCheckScript());
}

if(txtAvePrice!=null)
{txtAvePrice.Attributes.Add("onblur","ClientCheckFunction('"+txtAvePrice.ClientID+"',6,2)");}
}

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


{
return@"<scriptlanguage=""javascript"">
functionClientCheckFunction(strid,nInt1,nInt2)
{
if(isNaN(document.getElementById((strid).value))
{
alert(""您输入的不是合法的数字。"");
document.getElementById((strid).focus();
document.getElementById((strid).select();
returnfalse;
}
varsm='^(//d){1,'+nInt1+'}$|^(//d){1,'+nInt1+'}//.(//d){1,'+nInt2+'}$';
varm=newRegExp(sm);
if(!m.test(document.getElementById((strid).value))
{
alert('输入的数字整数位最多'+nInt1+'位,小数位最多'+nInt2+'位');
document.getElementById((strid).focus();
document.getElementById((strid).select();
returnfalse;
}
returntrue;
}</script>";
}















































第二步,服务器端验证:以GridView为例
前台页面:
<!--{cps..3}-->
<asp:GridViewID="GVList"runat="server"ShowFooter="true"AutoGenerateColumns="False"
BorderStyle="Solid"BorderColor="#ffffff"GridLines="Horizontal"CellSpacing="1"
Width="640"HorizontalAlign="center"BorderWidth="0px"EnableViewState="true"
DataKeyNames="CustomID">
<HeaderStyleBackColor="#1C5E55"ForeColor="White"HorizontalAlign="center"Height="30px"/>
<AlternatingRowStyleBackColor="#f7f7f7"/>
<RowStyleHorizontalAlign="center"Height="25px"BackColor="#E3EAEB"/>
<SelectedRowStyleBackColor="#C5BBAF"Font-Bold="True"ForeColor="#333333"/>
<Columns>
<asp:TemplateField>
<HeaderStyleWidth="60px"BackColor="#1C5E55"ForeColor="White"/>
<HeaderTemplate>
分类编号</HeaderTemplate>
<ItemTemplate>
<asp:LabelID="PKID"Text='<%#DataBinder.Eval(Container.DataItem,"CustomID")%>'
runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderStyleWidth="60px"BackColor="#1C5E55"ForeColor="White"/>
<HeaderTemplate>
单位</HeaderTemplate>
<ItemTemplate>
<asp:LabelID="C_Unit"Text="元/公斤"runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最高价</HeaderTemplate>
<ItemTemplate>
最高价:
<asp:TextBoxID="txtMaxPrice"runat="Server"CssClass="PriceStyle"MaxLength="6"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
最低价
</HeaderTemplate>
<ItemTemplate>
最低价:<asp:TextBoxID="txtMinPrice"runat="Server"CssClass="PriceStyle"MaxLength="6"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
平均价</HeaderTemplate>
<ItemTemplate>
平均价:
<asp:TextBoxID="txtAvePrice"runat="Server"CssClass="PriceStyle"MaxLength="6"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ButtonID="btnInsert"Text="上传所填数据"runat="server"OnClientClick="javascript:returnconfirm('每天只能上传一次,重复上传会替换今日已上传的数据,确认要上传您的报价信息吗?')"/>





















































后台代码:
<!--{cps..8}-->
privatevoidbtnInsert_Click(objectsender,EventArgse)


{
stringstr=CheckValid();

if(str.Trim().Length>0)
{this.Debug(str,this.ClientID);return;}

try
{AddOneRecord();}
catch(Exceptionex)


{

LoghandlebyTony2008.11.21#regionLoghandlebyTony2008.11.21
//stringloginid=EmptyString;
//myLogger.Error(GetErrorMessage(loginid,1),ex);
//Debug(ErrorHandle.GetErrorInfoByID(999),this.ClientID);return;
#endregion
}
}
privatestringCheckValid()


{
stringstr=string.Empty;

if(null==GVList)
{str="上传数据为空!";returnstr;}
stringstrPre1=ErrorHandle.GetErrorInfoByID(155);//获取错误信息
stringstrPre2=ErrorHandle.GetErrorInfoByID(156);//获取错误信息
TestProj.Price.Framework.Components.Price2p=newTestProj.Price.Framework.Components.Price2();


Checkinput////tony2008.12.16#regionCheckinput////tony2008.12.16
foreach(GridViewRowgvrinGVList.Rows)


{
Labellb=(Label)(gvr.FindControl("PKID"));
if(lb!=null)


{
inttemp=SQLParser.IntParse(lb.Text);

if(temp>0)
{p.P_Cate="---编号["+temp+"]";}
}
//验证平均价
TextBoxtb=(TextBox)(gvr.FindControl("txtAvePrice"));

if(tb==null||tb.Text==EmptyString)
{str=strPre1;returnstr+p.P_Cate;}

try
{p.P_AverPrice=Double.Parse(tb.Text.Replace(dunhao,numberdot));}

catch
{str=strPre2;returnstr+p.P_Cate;}
//验证最低价
tb=(TextBox)(gvr.FindControl("txtMinPrice"));

if(tb==null||tb.Text==EmptyString)
{str=strPre1;returnstr+p.P_Cate;}

try
{p.P_MinPrice=Double.Parse(tb.Text.Replace(dunhao,numberdot));}

catch
{str=strPre2;returnstr+p.P_Cate;}
//验证最高价
tb=(TextBox)(gvr.FindControl("txtMaxPrice"));

if(tb==null||tb.Text==EmptyString)
{str=strPre1;returnstr+p.P_Cate;}

try
{p.P_MaxPrice=Double.Parse(tb.Text.Replace(dunhao,numberdot));}

catch
{str=strPre2;returnstr+p.P_Cate;}


if(p.P_MinPrice>p.P_MaxPrice)
{str=ErrorHandle.GetErrorInfoByID(157);returnstr+p.P_Cate;}

if(p.P_AverPrice<p.P_MinPrice)
{str=ErrorHandle.GetErrorInfoByID(158);returnstr+p.P_Cate;}

if(p.P_AverPrice>p.P_MaxPrice)
{str=ErrorHandle.GetErrorInfoByID(159);returnstr+p.P_Cate;}
}
#endregion
returnstr;
}


































































































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