Allow only decimal numbers in textbox in C#

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!

Leave a Comment