How do I make a textbox that only accepts numbers?

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

    Both integers and floats need to be accepted, including the negative numbers.

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        // Text
        string text = ((Control) sender).Text;
    
        // Is Negative Number?
        if (e.KeyChar == '-' && text.Length == 0)
        {
            e.Handled = false;
            return;
        }
    
        // Is Float Number?
        if (e.KeyChar == '.' && text.Length > 0 && !text.Contains("."))
        {
            e.Handled = false;
            return;
        }
    
        // Is Digit?
        e.Handled = (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar));
    }
    
    0 讨论(0)
  • 2020-11-21 06:53

    Try a MaskedTextBox. It takes a simple mask format so you can limit the input to numbers or dates or whatever.

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

    You can use the TextChanged event

    private void textBox_BiggerThan_TextChanged(object sender, EventArgs e)
    {
        long a;
        if (! long.TryParse(textBox_BiggerThan.Text, out a))
        {
            // If not int clear textbox text or Undo() last operation
            textBox_LessThan.Clear();
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:53

    I would handle it in the KeyDown event.

    void TextBox_KeyDown(object sender, KeyEventArgs e)
            {
                char c = Convert.ToChar(e.PlatformKeyCode);
                if (!char.IsDigit(c))
                {
                    e.Handled = true;
                }
            }
    
    0 讨论(0)
  • 2020-11-21 06:53

    Sorry to wake the dead, but I thought someone might find this useful for future reference.

    Here is how I handle it. It handles floating point numbers, but can easily be modified for integers.

    Basically you can only press 0 - 9 and .

    You can only have one 0 before the .

    All other characters are ignored and the cursor position maintained.

        private bool _myTextBoxChanging = false;
    
        private void myTextBox_TextChanged(object sender, EventArgs e)
        {
            validateText(myTextBox);
        }
    
        private void validateText(TextBox box)
        {
            // stop multiple changes;
            if (_myTextBoxChanging)
                return;
            _myTextBoxChanging = true;
    
            string text = box.Text;
            if (text == "")
                return;
            string validText = "";
            bool hasPeriod = false;
            int pos = box.SelectionStart;
            for (int i = 0; i < text.Length; i++ )
            {
                bool badChar = false;
                char s = text[i];
                if (s == '.')
                {
                    if (hasPeriod)
                        badChar = true;
                    else
                        hasPeriod = true;
                }
                else if (s < '0' || s > '9')
                    badChar = true;
    
                if (!badChar)
                    validText += s;
                else
                {
                    if (i <= pos)
                        pos--;
                }
            }
    
            // trim starting 00s
            while (validText.Length >= 2 && validText[0] == '0')
            {
                if (validText[1] != '.')
                {
                    validText = validText.Substring(1);
                    if (pos < 2)
                        pos--;
                }
                else
                    break;
            }
    
            if (pos > validText.Length)
                pos = validText.Length;
            box.Text = validText;
            box.SelectionStart = pos;
            _myTextBoxChanging = false;
        }
    

    Here is a quickly modified int version:

        private void validateText(TextBox box)
        {
            // stop multiple changes;
            if (_myTextBoxChanging)
                return;
            _myTextBoxChanging = true;
    
            string text = box.Text;
            if (text == "")
                return;
            string validText = "";
            int pos = box.SelectionStart;
            for (int i = 0; i < text.Length; i++ )
            {
                char s = text[i];
                if (s < '0' || s > '9')
                {
                    if (i <= pos)
                        pos--;
                }
                else
                    validText += s;
            }
    
            // trim starting 00s 
            while (validText.Length >= 2 && validText.StartsWith("00")) 
            { 
                validText = validText.Substring(1); 
                if (pos < 2) 
                    pos--; 
            } 
    
            if (pos > validText.Length)
                pos = validText.Length;
            box.Text = validText;
            box.SelectionStart = pos;
            _myTextBoxChanging = false;
        }
    
    0 讨论(0)
  • 2020-11-21 06:53

    This one works with copy and paste, drag and drop, key down, prevents overflow and is pretty simple

    public partial class IntegerBox : TextBox 
    {
        public IntegerBox()
        {
            InitializeComponent();
            this.Text = 0.ToString();
        }
    
        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }
    
        private String originalValue = 0.ToString();
    
        private void Integerbox_KeyPress(object sender, KeyPressEventArgs e)
        {
            originalValue = this.Text;
        }
    
        private void Integerbox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if(String.IsNullOrWhiteSpace(this.Text))
                {
                    this.Text = 0.ToString();
                }
                this.Text = Convert.ToInt64(this.Text.Trim()).ToString();
            }
            catch (System.OverflowException)
            {
                MessageBox.Show("Value entered is to large max value: " + Int64.MaxValue.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Text = originalValue;
            }
            catch (System.FormatException)
            {                
                this.Text = originalValue;
            }
            catch (System.Exception ex)
            {
                this.Text = originalValue;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK , MessageBoxIcon.Error);
            }
        }       
    }
    
    0 讨论(0)
提交回复
热议问题