Some useful TextBox Validations in Windows Application

vishalneeraj-24503
Posted by vishalneeraj-24503 under C# category on | Points: 40 | Views : 1057
Hi All,

Textbox validation is easy in Windws Application.
As we know that,Dot Net has introduced lots of Textbox events which is used for validating textbox inputs.

Generally KeyPress event is mostly used.

For Example:-

If we want to have only Numeric Values entered into Textbox,then inside Keypress event,we will write as :-

private void txt_age_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar)))
{
e.Handled = true;
}
}


If we want to have only Character Values entered into Textbox,then inside Keypress event,we will write as :-

private void txt_name_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (!(char.IsLetter(e.KeyChar) || char.IsControl(e.KeyChar)))
{
e.Handled = true;
}
}


If we want to have only CAPITAL LETTERS and Character Values entered into Textbox,then inside Keypress event,we will write as :-

Here,IsUpper method will be used to have all the characters in upper case only

private void txt_name_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (!(char.IsUpper(e.KeyChar) || char.IsControl(e.KeyChar)))
{
e.Handled = true;
}
}


If we want to have only SMALL LETTERS and Character Values entered into Textbox,then inside Keypress event,we will write as :-

Here,IsLower method will be used to have all the characters in lower case only

private void txt_name_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (!(char.IsLower(e.KeyChar) || char.IsControl(e.KeyChar)))
{
e.Handled = true;
}
}


If we want to have only Numeric Values as well as Decimal Values entered into Textbox,then inside Keypress event,we will write as :-

private void txt_age_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || (e.KeyChar == (char)46)))
{
e.Handled = true;
}
}

Comments or Responses

Posted by: Sheonarayan on: 12/16/2013 Level:HonoraryPlatinum | Status: [Administrator] | Points: 10
Good one Vishal!

Login to post response