2

Recently I've notice, some smart user pass string (alphabets) in the TextBox that allow only number value (0-9) during KeyPress Event in one my projects. Unfortunately the database column type in NVARCHAR, that's why data inserting operation is completing with with invalid data. My project (Winform) is big enough to change data type of that column (NVARCHAR to INT). I got error while calculating SUM of that column in SQL Server. Here is my KeyPress Event for number only validation.

private void txtInputValue_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar)) e.Handled = true;         //Just Digits
    if (e.KeyChar == (char)8) e.Handled = false;            //Allow Backspace
}

Now how can I prevent user to stop paste some invalid data except Number (0-9). Thanks in advance for help me.

5
  • 2
    TextBox.ShortcutsEnabled = false ? Commented Dec 11, 2014 at 12:57
  • Is your project WinForms, WPF or something else? Commented Dec 11, 2014 at 12:58
  • It's likely WinForms since the event handler is giving a KeyPressEventArgs. Commented Dec 11, 2014 at 12:59
  • 2
    I'd suggest not checking inputs on every keypress event, but rather wait for the textchanged event and then check whether it is valid input to you (i.e. numeric or what have you), that way you also dont rob the user of well known practices such as copypasting. Commented Dec 11, 2014 at 13:00
  • Another approach (not as good as MaskedTextBox, but still user friendly) is to let user type in anything (it should be clear what input is expected though), but validate value as it's changed (in TextChanged event handler). Validation result can be displayed to user, so that he can correct his mistake, without restricting his input. Good example is entering double values. If double.TryParse fails, then you can display red border or some icon to inform user what input is wrong. This approach is very good to handle special cases (blank values, constants: NaN, +Infinity, etc.). Commented Dec 11, 2014 at 13:34

3 Answers 3

3

Assuming your project is WinForms - you are heading the wrong way.

It looks like all you need - is MaskedTextBox.

In that control you can set the Mask property for "digits only" mask preventing input of "non-digit" characters not only from keyboard, but also from pasting.

See MSDN for reference about mask format.

Sign up to request clarification or add additional context in comments.

Comments

3

You can simply set the ShortcutsEnabled of your textbox to false. (As suggested by Sriram Sakthivel)

txtInputValue.ShortcutsEnabled = false;

Comments

0

With KeyPress add TextChanged event also as like,

    private void txtInputValue_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit(e.KeyChar)) e.Handled = true;         //Just Digits
        if (e.KeyChar == (char)8) e.Handled = false;            //Allow Backspace
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
        {
            MessageBox.Show("Please enter only numbers.");
            textBox1.Text = string.Empty;
        }
    }

Hope this helps...

7 Comments

This suggestion is a usability horror: don't use MessageBox and certainly don't clear the entire textbox when one wrong character has been entered.
@CodeCaster Wrong character will be prevented by KeyPress event and this will pop-up only for pasted text...
And now it doesn't allow using the arrow keys, and still clears the entire textbox when the user manages to get one non-numeric character in there. Do not reinvent the wheel poorly. Use a masked textbox or tested code.
@CodeCaster I accept masked textbox is the solution, but the combination of KeyPress and TextChanged events works for me, I have tested it with my knowledge. Only when there is a paste of alphabets from mouse pointer, it clears the text.
@CodeCaster Sometimes reinventions give better options...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.