How do I make a textbox that only accepts numbers?

后端 未结 30 1590
梦如初夏
梦如初夏 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: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*$") { }
    }
    

提交回复
热议问题