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

Text box to accept only number

4.33/5 (12 votes)
24 Apr 2011CPOL 64.6K  
The following Class is a TextBox for WinForms that only accepts 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (numerics) or backspace as input. Not using regular expressions.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;namespace...
The following Class is a TextBox for WinForms that only accepts 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (numerics) or backspace as input. Not using regular expressions.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyControls
{
    class NumericTextBox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            // Check if the pressed character was a backspace or numeric.
            if (e.KeyChar != (char)8  && !char.IsNumber(e.KeyChar))
            {
                e.Handled = true;
            }
        }
    }
}

License

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