65.9K
CodeProject is changing. Read more.
Home

Custom Control: Numeric TextBox: TextBox that alow you to enter only numbers

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.10/5 (9 votes)

Jan 29, 2007

viewsIcon

55850

Sometimes we need to control the user input to some specific values. The following article explain how to do this with a TextBox

Introduction

Sometimes we need to control the user input. This control is a normal TextBox, with the property that the control accept only numeric values!

because this control is a TextBox, we inherit from the base class like this NumericTextBox : TextBox

What we have to do is to override the events OnKeyPress and OnKeyDown for the control. The full code is this:


using System.Windows.Forms;
using System.ComponentModel;

namespace MyCustomControls
{
    [Description("Numeric TextBox")]
    public class NumericTextBox : TextBox
    {
        private bool nonNumberEntered = false;

        public NumericTextBox()
        {
            this.Width = 150;
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (nonNumberEntered == true)
            {
                e.Handled = true;
            }
        }
        protected override void OnKeyDown(KeyEventArgs e)
        {
            nonNumberEntered = false;
            if (e.Shift == true || e.Alt == true)
            {
                nonNumberEntered = true;
                return;
            }
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    if (e.KeyCode != Keys.Back)
                    {
                        nonNumberEntered = true;
                    }
                }
            }
        }
    }
}



Now, all we have to do is to use it in our application.
This code can be improved. Now it's possible to Paste from clipboard non numeric values. Next version (I'll write this in few days) will contain this improvements!