How to block or restrict special characters from textbox

The code below allows only numbers, letters, backspace and space.

I included VB.net because there was a tricky conversion I had to deal with.

C#

private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
}

VB.net

Private Sub textBoxSample_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBoxSample.KeyPress
    e.Handled = e.KeyChar <> ChrW(Keys.Back) And Not Char.IsSeparator(e.KeyChar) And Not Char.IsLetter(e.KeyChar) And Not Char.IsDigit(e.KeyChar) 
End Sub

you can use this:

private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
    }

it blocks special characters and only accept int/numbers and characters


I am assuming you are trying to keep only alpha-numeric and space characters. Add a keypress event like this

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    var regex = new Regex(@"[^a-zA-Z0-9\s]");
    if (regex.IsMatch(e.KeyChar.ToString()))
    {
        e.Handled = true;
    }
}

Tags:

C#

Winforms