C# Textbox - enter only positive numbers on KeyPress event in Windows form application

2017/10/05 02:27

To prevent users from entering incorrect data in Windows form application, set restriction to allow only specific characters to be entered in the text box.
This example uses KeyPress event to monitor the users input and to apply the restriction required.
To avoid code duplication in Windows multiform applications for example, a separate class file is created “CommonFunctions.cs”.

The function to allow only numbers in textbox control is named InputNumbers.

For each Windows form, create a single KeyPress event and call the InputNumbers function inside it.

public void InputNumbers(object sender, KeyPressEventArgs e)
    // Get the decimal symbol format defined in your regional settings.
    char decimalSeparator = Convert.ToChar(CultureInfo.CurrentCulture. 
    // Check if pressed key is not a control key, digit key and decimal separator key.
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) 
              && (e.KeyChar != decimalSeparator))
        // Convert the sender to TextBox.
        TextBox toolTippedControl = sender as TextBox;
        // Create ToolTip parameters.
        string toolTipText = "Input field can only contain the following characters:"
                + "\n\t- Numbers: 0123456789"
                + "\n\t- Decimal Separator";
        int toolTipPosX = toolTippedControl.Width;
        int toolTipPosY = 0;
        int toolTipDuration = 4000;
        // Create a ToolTip object.
        ToolTip toolTip = new ToolTip();
                        // Set ToolTip icon.
        toolTip.ToolTipIcon = ToolTipIcon.Warning;
        // Pass the created ToolTip parameters and show it.
        toolTip.Show(toolTipText, toolTippedControl, toolTipPosX, toolTipPosY, toolTipDuration);
                        // Set Handled method to true to cancel the button press.
        e.Handled = true;
    // Decimal separator symbol must be only one, so:
    // Check if the decimal separator key is pressed.
    // And check if the TextBox already have entered symbol for decimal separator.
    if ((e.KeyChar == decimalSeparator) && 
            ((sender as TextBox).Text.IndexOf(decimalSeparator) > -1))
        // Set Handled method to true to cancel the button press.
        e.Handled = true;

In each Windows application form:
1. Create an instance of the class:
CommonFunctions commonFunc = new CommonFunctions();
2. Create function which will be representing the event. Inside it, call the function from the “CommonFunctions.cs” class file.
private void InputNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
    commonFunc.InputNumbers(sender, e);
Now, using the designer on each form assign The “InputNumbersOnly_KeyPress” to the KeyPress event of the TextBox control.

You can select multiple TextBoxes and assign the KeyPress event to them.