TextBox Validation
In some cases I want to restricted that my textbox accept only specific input which we want. That means in name’s textbox no one can enter special and numeric etc character. Like this salary’s textbox user entered only numeric values.
Character Validation
In this case user entered only character in texbox with backspace and space buttons.
private void txtName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);
}
Numeric Validation
In this case user entered only numeric values in textbox with back button.
private void txtAge_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = !(char.IsNumber(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
Numeric with Decimal Validation
In this case user entered only decimal values in textbox with back button
private void txtSalary_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = !(char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == (char)Keys.Back);
}
Anonymous User
08-Apr-2019Very helpful article.
Sunil Singh
14-Jul-2017This post added some useful knowledge to me. Thanks