Allowing only Alphanumeric Characters on a TextBox

If you don't want to allow any other characters entry except for the alphanumeric characters in a TextBox, then you can do this on the KeyPress event of a TextBox.

In the KeyPress Event, you need to check whether the entered character is either a Letter or a Digit.

 Char.IsLetterOrDigit(e.KeyChar)

If yes, then allow the Key pressing by setting

"e.Handled = false"

Otherwise, don't allow the Key pressing by setting "e.Handled = true"

In addition to the alphanumeric characters, generally one should allow the backspace character too along with the alphanumeric characters so that the user can remove any wrong character if he entered by mistake.

In order to do that, you need to add one more condition in the if block as

private void textBox_KeyPress(object sender, KeyPressEventArgs e)

{

    if (Char.IsLetterOrDigit(e.KeyChar)     // Allowing only any letter OR Digit

            ||e.KeyChar == '\b')                 // Allowing BackSpace character

    {

        e.Handled = false;

    }

    else

    {

        e.Handled = true;

    }

}