-7

I'm new in C# and I would like to know how I can make a textbox that only accepts numbers. So if you type a decimal number it would be no problem but when you type something else then "0,1,2,3,4,5,6,7,8,9 or ," I would like to have it deleted in the textbox. I thought it is possible with KeyDown or TextChanged.

This is what I've tried already:

private void txt2011_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (!System.Text.RegularExpressions.Regex.IsMatch("^[0-9]", txt2011.Text))
        {
            txt2011.Text = "0";
        }
    }

Thanks in advance

  • 1
    http://stackoverflow.com/questions/19715303/regex-that-accepts-only-numbers-0-9-and-no-characters – ken lacoste Sep 24 '15 at 09:22
  • 1
    What about `-1` (note `-`) or `1e+2` (`100` in exponential notation) or `1,2,3` (note *two* commas)? – Dmitry Bychenko Sep 24 '15 at 09:22
  • I find that validation *while typing* often annoys the user and is difficult to get right. Perhaps you could validate the field using the `Leave` event instead? (Maybe change the background colour or display a message to show it is invalid?) – Ulric Sep 24 '15 at 09:32

2 Answers2

2

Although NumericUpDown is a good choice, but you want a textbox after all, right?

Here is a general guide. First you need to subscribe to the TextChanged event of the textbox. This can be done by double clicking the textbox in the designer. When the event happens, you want to check the textbox's text. If it is empty string, just return. Now you can try to convert the text to a double. If it can't be converted, set the text to the original text.

You might want to have a originalText variable somewhere in the class. If it converts to a double successfully, set the original text to the text.

try {
    Convert.ToDouble(textbox1.Text);
} catch (NumberFormatException) {
    textbox1.Text = originalText;
    return;
}
originalText = textbox1.Text;

Now it should work!

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

KeyDown and Text Changed event will fire as soon as you start writing in TextBox. In that case, you will not even see the text that you have typed as the appropriate action will take place as soon as text is changed inside the textbox.

Better would be to use LostFocus event as it will fire only when the user has left that textbox and then you can highlight it and replace the text with 0.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
ankyAS
  • 301
  • 2
  • 11