Written: 28 October 2012
While doing a C# Windows Forms project, I needed a numeric textbox. On googling I found this. It pretty much did what I needed, but wanted to add these features-
Here is the modified code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace CustomeControls { class NumericTextbox : TextBox { bool allowSpace = false; bool allowNegative = true; // Restricts the entry of characters to digits (including hex), the negative sign, // the decimal point, and editing keystrokes (backspace). protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); System.Globalization.NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; string decimalSeparator = numberFormatInfo.NumberDecimalSeparator; string groupSeparator = numberFormatInfo.NumberGroupSeparator; string negativeSign = numberFormatInfo.NegativeSign; string keyInput = e.KeyChar.ToString(); if (Char.IsDigit(e.KeyChar)) { // Digits are OK } else if (keyInput.Equals(decimalSeparator)) { //Make sure there is only one decimal separator if (this.Text.IndexOf('.') != -1) e.Handled = true; } else if (this.allowNegative && keyInput.Equals(negativeSign)) { //The negative sign should be the first character if (this.SelectionStart != 0) e.Handled = true; } else if (keyInput.Equals(groupSeparator)) { // Decimal separator is OK } else if (e.KeyChar == '\b') { // Backspace key is OK } // else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0) // { // // Let the edit control handle control and alt key combinations // } else if (this.allowSpace && e.KeyChar == ' ') { } else { // Swallow this invalid key and beep e.Handled = true; //System.Media.SystemSounds.Beep.Play(); } } public int IntValue { get { return Int32.Parse(this.Text); } } public decimal DecimalValue { get { return Decimal.Parse(this.Text); } } public bool AllowSpace { set { this.allowSpace = value; } get { return this.allowSpace; } } public bool AllowNegative { set { this.allowNegative = value; } get { return this.allowNegative; } } } }