2

I wish to validate this TextBox against negative values and characters (must be integer without decimal) It works well for . but I am not able to understand why it accepts negative value and characters?

My code is :

private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar) && (e.KeyChar == '.') && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back))
        e.Handled = true;
}

1 Answer 1

1

You need to replace the first && operator with || and also move it to the end of your if statement then it should works as you want. Like this:

private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar) && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back) || (e.KeyChar == '.'))
        e.Handled = true;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yaah thanks it worked, But why i needed to replace && with or ?
@testtest ... Because you don't want to evaluate the second operand which validates for . with the first operand. If the second operand evaluates to true e.Handled should be true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.