-1

Good day. I'm having a hard time with this. TextBox1 should only accept numbers and if the user input a text, a message box will pop-up saying that only numbers can be entered.

I don't know how to do this since the message box should pop-up without clicking any button.

The user will just really enter numbers and if they enter non numerical value the message box will appear instantly.

Is this even possible?

I've tried the KeyPress events but I can still input letters. Please help.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
MULTI FANDOM
  • 3
  • 1
  • 4
  • please show us your code for the event handler, yes KeyPress events are a good place to start, in that event handler you need to check for a non-numeric key and show the dialog and cancel the event. This is actually a very standard example, read the docs https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keyeventhandler?view=windowsdesktop-6.0 – Chris Schaller Feb 21 '22 at 03:43
  • 2
    It is possible; however I would reconsider popping up an error dialog that the user has to close. I would simply ignore the invalid keys that are pressed. The user will figure this out quickly, no need for an annoying popup. Using the `TextBoxes` `KeyPress` event should enable you to do this however, since there is no code showing how you implement this… speculation is all you may get. – JohnG Feb 21 '22 at 03:48
  • 2
    It sounds like you should be using `MaskedTextBox` or `NumericUpDown`. – rfmodulator Feb 21 '22 at 03:53

1 Answers1

0

This is a very standard implementation, with a minor twist of including a dialog box. In general a dialog box is just going to annoy the user and take the focus away from the form, it breaks the flow of the user interaction so we try to avoid it, however you can adapt the standard example listed in the MS Docs - KeyEventHandler Delegate documentation:

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
        MessageBox.Show("Only numeric input is accepted");
    }
}

Using the KeyEventArgs in this manner allows you access to the raw physical key that was pressed, and to separately prevent the textbox from accepting the key press.

This style of code is very useful when 3rd party controls (or your own code) has overriden the standard implementations. It is however possible to do it all in the KeyPress event handler:

private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (!Char.IsNumber(e.KeyChar) && e.KeyChar != '.')
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
        MessageBox.Show("Only numeric input is accepted");
    }
}

But that could still allow us to enter a value of "12.333...44..5" so a more complete example should extend one of the previous examples and compare against the current value in the textbox:

private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    bool isNumber = Char.IsNumber(e.KeyChar);
    if (e.KeyChar == '.')
    {
       isNumber = !(sender as TextBox).Text.Contains(".");
    }

    if (!isNumber)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
        MessageBox.Show("Only numeric input is accepted");
    }
}
Chris Schaller
  • 13,704
  • 3
  • 43
  • 81
  • But the input can't be deleted? Is it possible to add the Keys. Back? So that I can still delete it. – MULTI FANDOM Feb 21 '22 at 05:46
  • If you want to, just don't set `e.Handled - true` (see the comment immediately before that line) if you are going to allow the input, a message box is really the wrong way to go, a warning indicator on the page is fine, but then you would use `TextChanged` event. Would you use software that displayed a popup in the middle of typing that still allowed the content to stay, you would then also have to code up some validation on the form before it was _submitted_. The point of handling key event args is to prevent bad use input. – Chris Schaller Feb 21 '22 at 06:10