Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / IIS

Simple NumericTextBox Web Custom Control

2.60/5 (2 votes)
14 Jul 2007CPOL2 min read 1   214  
A simple textbox control allowing only integer input.

Introduction

Just a simple textbox control which allows only integer input using client-side JavaScript code. It also provides a property of type int so that setting and getting the value of the control is made much easier.

Using the code

Using NumericTextBox is as simple as using the built-in TextBox control. The value of NumericTextBox can be changed either at design time through the Designer or at runtime through code.

Screenshot - n1.jpg

ASP.NET
<body>
    <form id="form1" runat="server">
        <cc1:NumericTextbox ID="NumericTextbox1" 
            runat="server" Value="76">76</cc1:NumericTextbox>
    </form>
</body>

The NumericTextBox control provides a public property for getting or setting its integer value:

C#
[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(); }
}

Let's see what happens on the prerender event of NumericTextBox:

C#
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);
}

As we see in the above code, the handling of the KeyPress event is assigned to a client-side JavaScript function named IsNumeric(). This function returns true if the key pressed was a valid numeric key and false otherwise. So any invalid key press is ignored.

Because of the different ways the various browsers handle the keypress event, the value of the key pressed is assigned to a local variable keynum in a different way depending on the browser used. So, if the browser being used is Internet Explorer, the value is taken from the keyCode property of the event object; otherwise the value is taken from the 'which' property of the event object.

The function returns true on the following circumstances:

  1. The key pressed was a numeric key (0-9), having a key number from 48 (the key number of zero) to 57 (the key number of nine)
  2. The key pressed was the minus sign (-) , only if it is the first character of the input text of the textbox
  3. The key pressed was the delete key (key number 8)
  4. The key pressed was the backspace key (key number 127)

Conclusion

This is just a simple custom control mostly inspired by various JavaScript codes implementing numeric validation available on the Internet. Future improvements could be decimal number support and overflow/underflow check.

Thanks for reading!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)