原来控制TextBox只能输入数字是如此简单
在做WEB开发的时候难免会要控制TextBox只能输入数字的情况,怎么办呢,搞个验证控件再加上正则表达或是用javascript脚本来控制,
在以前的开发中我都是用以上的俩种方法来判断,这样做其实不是不行,但最近在学习组件开发,原来是可以把TextBox重写的,这样可以
把控制输入数字的脚本封装在控件里面,这样就只需要拖出来就能用了,不用每次都去写判断了,岂不美哉!
其实,我也是个新手,把做过的东西写在这里只是为了更加巩固自己的知识,有哪里写的不好,方法欠妥当的,还往高手多多指点!
下面是这个自定义控件的源码
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
namespace SmbComponent.EditorSuite
{
public class NumberEditor :TextBox {
private const string SMB_NUMBER_SCRIPT_ID = "{9698eb3d-cb91-47cc-8ad8-aa3e7a4b4acd}";
private const string SMB_NUMBER_SCRIPT_ONLY_HOOK = "return NumberEditor_KeyPress_Handle(this)";
private const string SMB_NUMBER_SCRIPT_ONLY_SCRIPT = "<script language=\"javascript\">\n" +
"function NumberEditor_KeyPress_Handle(ctrl)\n{{" +
"if(event.keyCode == 13) \n return true;\n" +
"if(event.keyCode<48 || event.keyCode>57 )\n" +
"return false;\n else \n return true;\n}}" +
"</script>";
private void RenderJavscript()
{
if (!Page.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))
{
Page.RegisterClientScriptBlock(SMB_NUMBER_SCRIPT_ID, string.Format(SMB_NUMBER_SCRIPT_ONLY_SCRIPT, base.ID));
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute("OnKeyPress", SMB_NUMBER_SCRIPT_ONLY_HOOK);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
RenderJavscript();
}
public NumberEditor()
: base()
{ }
}
}
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
namespace SmbComponent.EditorSuite
{
public class NumberEditor :TextBox {
private const string SMB_NUMBER_SCRIPT_ID = "{9698eb3d-cb91-47cc-8ad8-aa3e7a4b4acd}";
private const string SMB_NUMBER_SCRIPT_ONLY_HOOK = "return NumberEditor_KeyPress_Handle(this)";
private const string SMB_NUMBER_SCRIPT_ONLY_SCRIPT = "<script language=\"javascript\">\n" +
"function NumberEditor_KeyPress_Handle(ctrl)\n{{" +
"if(event.keyCode == 13) \n return true;\n" +
"if(event.keyCode<48 || event.keyCode>57 )\n" +
"return false;\n else \n return true;\n}}" +
"</script>";
private void RenderJavscript()
{
if (!Page.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))
{
Page.RegisterClientScriptBlock(SMB_NUMBER_SCRIPT_ID, string.Format(SMB_NUMBER_SCRIPT_ONLY_SCRIPT, base.ID));
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute("OnKeyPress", SMB_NUMBER_SCRIPT_ONLY_HOOK);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
RenderJavscript();
}
public NumberEditor()
: base()
{ }
}
}
其实验证是否数字还是通过javascript脚来验证,这里只是把脚本封装在控件中了.
其中有俩个关键点:
1,一定要绘制状态之前注册js脚本,那这个位置是哪里呢,就是在OnPreRender(EventArgs e)中来完成,如果是在绘制状态完成之后再注册脚本就没有用了
2,给控件添中属性,一定要在绘制Html标记之前添加,如果等到绘制Html标记完成之后一切就晚了.
那么在绘制Html标记结束之前就是在AddAttributesToRender中了,因为AddAttributesToRender是被RenderBeginTag调用的.