How can I prevent paste the string (a-z) in Textbox (Number Only) in C #

advertisements

This question already has an answer here:

  • how to make textbox who only allow integer value? 5 answers

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.


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.