Making C# Winform Textbox control Alphanumeric

First add a KeyPress event handler to the textbox object

this.textBoxMine.KeyPress += new 
System.Windows.Forms.KeyPressEventHandler(textBoxMine_KeyPress);

Then implemented the event handler textBoxMine_KeyPress

private void textBoxMine_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar) || char.IsNumber(e.KeyChar) ||
char.IsLetter(e.KeyChar))
{
return;
}
e.Handled = true;
}

char.IsControl is so backspace and space or delete will be returned true.

char.IsNumber is so if number is typed it will be returned true.

char.IsLetter is so if letter is typed it will return true.

And if it is returned true we do nothing so the typed char will be displayed in the textbox

else we will cancel the event (e.handled = true) so any other characters that would be typed in the textbox would be cancel and should not shown in the textbox e.g special characters.

Leave a Reply

Your email address will not be published. Required fields are marked *