IIS 5.1IIS 6.0IIS 7.0IISWebFormsVisual Studio 2005.NET 2.0C# 2.0C# 3.0中级开发Visual StudioJavascriptWindows.NETASP.NETC#
简单的数字文本框 Web 自定义控件






2.60/5 (2投票s)
一个简单的文本框控件,只允许整数输入。
引言
只是一个简单的文本框控件,它只允许使用客户端 JavaScript 代码进行整数输入。它还提供一个 int
类型的属性,以便更轻松地设置和获取控件的值。
使用代码
使用 NumericTextBox
与使用内置 TextBox
控件一样简单。 NumericTextBox
的值可以在设计时通过设计器或在运行时通过代码进行更改。
<body>
<form id="form1" runat="server">
<cc1:NumericTextbox ID="NumericTextbox1"
runat="server" Value="76">76</cc1:NumericTextbox>
</form>
</body>
NumericTextBox
控件提供一个公共属性,用于获取或设置其整数值
[Description ("The integer value of the NumericTextBox")]
public int Value
{
get
{
int ret;
// If text cannot be parsed as integer, return zero
// otherwise return the parsed integer
if (!int.TryParse(Text,out ret))
return 0;
return ret;
}
set { Text = value.ToString(); }
}
让我们看看 NumericTextBox
的 prerender
事件中发生了什么
protected override void OnPreRender(EventArgs e)
{
string scriptName = "ValidationScript";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptName))
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(),
scriptName,
"<script language="\""javascript\">" +
" function IsNumeric(e,elem) {" +
" var currentText = elem.value; " +
" if(window.event)" + // MSIE
" {" +
" keynum = e.keyCode;" +
" }" +
" else if(e.which)" + // Netscape/Firefox/Opera
" {" +
" keynum = e.which;" +
" }" +
// allow numeric keys
" return (keynum >= 48 && keynum <= 57) " +
// allow '-' only if it's the first char
" || (keynum == 45 && currentText == '') " +
// allow delete and backspace keys
" || (keynum == 8) || (keynum == 127); " +
" } </script>");
Attributes.Add("onKeyPress", "return IsNumeric(event,this)");
base.OnPreRender(e);
}
正如我们在上面的代码中看到的,KeyPress
事件的处理被分配给一个名为 IsNumeric()
的客户端 JavaScript 函数。 如果按下的键是有效的数字键,此函数返回 true
,否则返回 false
。 所以任何无效的按键都会被忽略。
由于各种浏览器处理 keypress
事件的方式不同,因此按下的键的值以不同的方式分配给局部变量 keynum
,具体取决于所使用的浏览器。 因此,如果使用的浏览器是 Internet Explorer,则该值取自事件对象的 keyCode
属性; 否则,该值取自事件对象的“which
”属性。
在以下情况下,该函数返回 true
- 按下的键是数字键 (0-9),键编号从 48(零的键编号)到 57(九的键编号)
- 按下的键是减号 (-),仅当它是文本框输入文本的第一个字符时
- 按下的键是删除键(键编号 8)
- 按下的键是退格键(键编号 127)
结论
这只是一个简单的自定义控件,主要受到 Internet 上各种实现数字验证的 JavaScript 代码的启发。 未来的改进可能包括小数支持和溢出/下溢检查。
感谢阅读!