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

WinForms TextBox to accept numbers in a range

4.43/5 (12 votes)
7 Jan 2012CPOL 72.7K  
Simple Numeric TextBox to accept digits for a given minimum maximum range
Sometime back, I was looking for a TextBox control which can silently accept numbers (positive int only) for a given range (minimum and maximum). I implemented the following simple class to achieve this:

C#
class NumberTextBox : System.Windows.Forms.TextBox
{
   private string mPrevious;
   private int mMin;
   private int mMax;

   public NumberTextBox() : this(0, Int32.MaxValue) { }
   public NumberTextBox(int min, int max)
      : base()
   {
      if ((min > max) || min < 0 || max < 0)
      {
         throw new Exception("Minimum and maximum values are not supported");
      }
      mMin = min;
      mMax = max;
      this.Text = min.ToString();
   }

   protected override void OnKeyPress(KeyPressEventArgs e)
   {
      mPrevious = this.Text;
      e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
   }

   protected override void OnTextChanged(EventArgs e)
   {
      if (this.Text == string.Empty)
      {
         return;
      }

      int num;
      if (Int32.TryParse(this.Text, out num))
      {
         if (num > mMax)
         {
            this.Text = mPrevious;
            this.Select(this.Text.Length, 0);
         }
      }
      else
      {
         this.Text = mPrevious;
         this.Select(this.Text.Length, 0);
      }
   }

   protected override void OnLeave(EventArgs e)
   {
      int num;
      if (!Int32.TryParse(this.Text, out num) || num < mMin || num > mMax)
      {
         this.Text = mPrevious;
         // To move the cursor at last
         this.Select(this.Text.Length, 0);
      }
   }
}


To use this NumberTextBox on your dialog/form, include the above class in the project and replace TextBox with NumberTextBox in your form.

License

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