Field level validation

Y

Yuelin

Hi all

I want to validate the textbox while user entering each character, I wrote:

private void txtAge_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
if (Char.IsLetter(e.KeyChar) == true)
{
MessageBox.Show("Age should not contain a letter" );
}
}


So whenever the user enters a character rather than a digit, the system will
pop up a message box.
But when clicking the OK button on the message box, the character is still
entered.

How can I prevent the character being entered when clciking the OK button?

Thanks

Yuelin
 
J

Jon Skeet

Yuelin said:
I want to validate the textbox while user entering each character, I wrote:

private void txtAge_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
if (Char.IsLetter(e.KeyChar) == true)
{
MessageBox.Show("Age should not contain a letter" );
}
}


So whenever the user enters a character rather than a digit, the system will
pop up a message box.
But when clicking the OK button on the message box, the character is still
entered.

How can I prevent the character being entered when clciking the OK button?

Setting e.Handled=true should do it, I believe.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top