Now most of the time the user needs validation in a Windows application, so before the user enters a wrong value (such as instead of text the user enters an integer) we can validate it using an event and some sort of coding.
For example in the following screen, a KeyPress event is created for the TextBox.

Now Create one Class Validation.cs and write the following code in it:
public void charonly(KeyPressEventArgs e)
{
if (Char.IsNumber(e.KeyChar) || Char.IsSymbol(e.KeyChar) || Char.IsWhiteSpace(e.KeyChar) || Char.IsPunctuation(e.KeyChar))
{
MessageBox.Show("Only Char are allowed");
e.Handled = true;
}
}
public void digitonly(KeyPressEventArgs e)
{
try
{
if (!(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || char.IsPunctuation(e.KeyChar)))
{
e.Handled = true;
MessageBox.Show("Enter only digit and decimal point.", "Alert!");
}
}
catch { }
}
Now call these two methods as per validation type (char or int) from the TextBox KeyPress Event:
validation v = new validation();
private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
{
v.digitonly(e); // allowing interger only
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
v.charonly(e); // allowing character only
}


Agasaud khanPosted Apr 10, 2014, 10:01 PM EDT
good
Asif KhanPosted Jan 17, 2012, 7:48 PM EST
good one
Mahamod GodaPosted Nov 10, 2011, 3:32 PM EST
it is good example
Shilpa KatrePosted Mar 28, 2011, 4:52 AM EDT
Good One
KayleighPosted Feb 24, 2011, 6:38 PM EST
Pretty useful...looking for your next post!
Sam HobbsPosted Feb 24, 2011, 4:39 PM EST
I think Microsoft's Windows Forms mislead developers into using code that is not the most object-oriented solutions. I don't know if someone has written an article showing an object-oriented design but if not then I hope someone does. Also, I think the catch block that just is "catch { }" is a bad example for beginners. I wish there was a comment someplace telling beginners not to use a catch block like that.
knightsPosted Feb 24, 2011, 10:58 AM EST
Good reference.Please spell check the code also to make it more readable. MessageBox.Show("Only Char are allwod"); "allowed" is misspelled in the previous line.Thank you.
Dinesh BeniwalTOP 10Posted Feb 23, 2011, 11:21 PM EST
Welcome to the C-sharp corner community.