How do I make a textbox that only accepts numbers?

后端 未结 30 1618
梦如初夏
梦如初夏 2020-11-21 06:05

I have a windows forms app with a textbox control that I want to only accept integer values. In the past I\'ve done this kind of validation by overloading the KeyPress event

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 06:37

    I've been working on a collection of components to complete missing stuff in WinForms, here it is: Advanced Forms

    In particular this is the class for a Regex TextBox

    /// Represents a Windows text box control that only allows input that matches a regular expression.
    public class RegexTextBox : TextBox
    {
        [NonSerialized]
        string lastText;
    
        /// A regular expression governing the input allowed in this text field.
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual Regex Regex { get; set; }
    
        /// A regular expression governing the input allowed in this text field.
        [DefaultValue(null)]
        [Category("Behavior")]
        [Description("Sets the regular expression governing the input allowed for this control.")]
        public virtual string RegexString {
            get {
                return Regex == null ? string.Empty : Regex.ToString();
            }
            set {
                if (string.IsNullOrEmpty(value))
                    Regex = null;
                else
                    Regex = new Regex(value);
            }
        }
    
        protected override void OnTextChanged(EventArgs e) {
            if (Regex != null && !Regex.IsMatch(Text)) {
                int pos = SelectionStart - Text.Length + (lastText ?? string.Empty).Length;
                Text = lastText;
                SelectionStart = Math.Max(0, pos);
            }
    
            lastText = Text;
    
            base.OnTextChanged(e);
        }
    }
    

    Simply adding something like myNumbericTextBox.RegexString = "^(\\d+|)$"; should suffice.

提交回复
热议问题