0

I have a textbox in C# where the user can enter only decimal numbers (negative and positive).

I don't want to use MaskedText Box, I would rather implement this using the keypress event to validate inputs.

How can I achieve this?

Thanks,

*********EDIT*********++

 private void mytextbox_KeyPress(object sender, KeyPressEventArgs e)
        {
   if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != '.' &&e.KeyChar!='-'))
            {
                e.Handled = true;
            }

            if (e.KeyChar == '.')
            {
                if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
                    e.Handled = true;
            }

          if (e.KeyChar=='-' && (sender as TextBox).SelectionStart > 0)
          {
                  e.Handled = true;
          }
}
Matimont
  • 739
  • 3
  • 14
  • 33

1 Answers1

0

TryParse for the various numeric types will tell you if the input is valid. For example, if you want to use a double:

private void OnKeyPress(...)
{
   double parsedValue = 0;
   if (double.TryParse(MyTextBox.Text, out parsedValue)
   {
       //Valid number entered, value in parsedValue
   }
   else
   {
       //Invalid number entered
   }
}

This answer has a lot of other ways to accompish this: How do I make a textbox that only accepts numbers?

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117