1

I'm trying to use this custom method for user input validation in text boxes. But I see something missing here as now I cannot move (focus) to next text box in the form!

private void textBox_Validating(object sender, CancelEventArgs e)
{
    TextBox currenttb = (TextBox)sender;
    if (currenttb.Text == "")
    {
        MessageBox.Show(string.Format("Empty field {0 }", currenttb.Name.Substring(3)));
        e.Cancel = false;
    }

    else
    {
        e.Cancel = true;
    }
}

Adding the handler to the textboxes with a foreach loop in the form constructor:

foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
    tb.Validating += textBox_Validating;
}
3
  • It is the expected behaviour - Control.Validating Event Commented Jun 19, 2014 at 9:00
  • There is a mistake in if. Should be like this > if (currenttb.Text == "") { MessageBox.Show(string.Format("Empty field {0 }", currenttb.Name.Substring(3))); e.Cancel = true ; } Commented Jun 19, 2014 at 9:05
  • if you set e.Cancel = true, means validation failed, then it will not allow to change the focus Commented Jun 19, 2014 at 9:07

1 Answer 1

1

As answerd here its expected behaviour of loosing the focus C# Validating input for textbox on winforms :-

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time or the Validating Event.

The Validating Event gets fired if your TextBox looses the focus, for example click on a other Control. If your set e.Cancel = true the TextBox don't loose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sign up to request clarification or add additional context in comments.

Comments

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.