How do I make a textbox that only accepts numbers?

后端 未结 30 1686
梦如初夏
梦如初夏 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: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);
            }
        }       
    }
    

提交回复
热议问题