How do I make a textbox that only accepts numbers?

后端 未结 30 1621
梦如初夏
梦如初夏 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:32

    I am assuming from context and the tags you used that you are writing a .NET C# app. In this case, you can subscribe to the text changed event, and validate each key stroke.

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
        {
            MessageBox.Show("Please enter only numbers.");
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:35

    you could use TextChanged/ Keypress event, use a regex to filter on numbers and take some action.

    0 讨论(0)
  • 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

    /// <summary>Represents a Windows text box control that only allows input that matches a regular expression.</summary>
    public class RegexTextBox : TextBox
    {
        [NonSerialized]
        string lastText;
    
        /// <summary>A regular expression governing the input allowed in this text field.</summary>
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual Regex Regex { get; set; }
    
        /// <summary>A regular expression governing the input allowed in this text field.</summary>
        [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.

    0 讨论(0)
  • 2020-11-21 06:38

    Using the approach described in Fabio Iotti's answer I have created a more generic solution:

    public abstract class ValidatedTextBox : TextBox {
        private string m_lastText = string.Empty;
        protected abstract bool IsValid(string text);
        protected sealed override void OnTextChanged(EventArgs e) {
            if (!IsValid(Text)) {
                var pos = SelectionStart - Text.Length + m_lastText.Length;
                Text = m_lastText;
                SelectionStart = Math.Max(0, pos);
            }
            m_lastText = Text;
            base.OnTextChanged(e);
        }
    }
    

    "ValidatedTextBox", which contains all nontrivial validation behavior. All that's left to do is inherit from this class and override "IsValid" method with whatever validation logic is required. For example, using this class, it is possible to create "RegexedTextBox" which will accept only strings which match specific regular expression:

    public abstract class RegexedTextBox : ValidatedTextBox {
        private readonly Regex m_regex;
        protected RegexedTextBox(string regExpString) {
            m_regex = new Regex(regExpString);
        }
        protected override bool IsValid(string text) {
            return m_regex.IsMatch(Text);
        }
    }
    

    After that, inheriting from the "RegexedTextBox" class, we can easily create "PositiveNumberTextBox" and "PositiveFloatingPointNumberTextBox" controls:

    public sealed class PositiveNumberTextBox : RegexedTextBox {
        public PositiveNumberTextBox() : base(@"^\d*$") { }
    }
    
    public sealed class PositiveFloatingPointNumberTextBox : RegexedTextBox {
        public PositiveFloatingPointNumberTextBox()
            : base(@"^(\d+\" + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + @")?\d*$") { }
    }
    
    0 讨论(0)
  • 2020-11-21 06:39
    int Number;
    bool isNumber;
    isNumber = int32.TryPase(textbox1.text, out Number);
    
    if (!isNumber)
    { 
        (code if not an integer);
    }
    else
    {
        (code if an integer);
    }
    
    0 讨论(0)
  • 2020-11-21 06:40

    Just use a NumericUpDown control and set those ugly up down buttons visibility to false.

    numericUpDown1.Controls[0].Visible = false;
    

    NumericUpDown is actually a collection of controls containing a 'spin box' (up down buttons), a text box and some code to validate and wange-jangle it all together.

    Marking:

    YourNumericUpDown.Controls[0].visible = false 
    

    will hide the buttons while keeping the underlying code active.

    While not being an obvious solution it is simple and effective. .Controls[1] would hide the text box portion if you wanted to do that instead.

    0 讨论(0)
提交回复
热议问题