Page 1 of 1

Form - Textbox - Numeric Only Entry

PostPosted: Sat Jun 17, 2017 3:29 pm
by Robertspark
To limit the input of a textbox to numbers, a single decimal place, and a single "-" entry at the start of the text box only

Code: Select all
        private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == '-')
            {
                if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
                {
                    e.Handled = e.KeyChar != (char)Keys.Back;
                }
                if ((e.KeyChar == '-') && ((sender as TextBox).Text.Length > 0))
                {
                    e.Handled = e.KeyChar != (char)Keys.Back;
                }
            }
            else
            {
                e.Handled = e.KeyChar != (char)Keys.Back;
            }
        }


Placed here as a code snippet (turned it into a function in my code) so that I can find it later.... :lol:

sure there are other solutions, but this one seems to be working for me at present.