有一個需求,需要在GridView中批量輸入數字!
於是想到封裝一個TextBox
代碼如下:
public class NumberText : TextBox
{
private const string SMB_NUMBER_SCRIPT_ID = "{c4f7dcfd-8f9b-4fe8-8bd1-4a8a1f145c0c}";
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.ClientScript.IsClientScriptBlockRegistered(SMB_NUMBER_SCRIPT_ID))
{
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), 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 NumberText()
: base()
{ }
}