CAD
CAD

Reputation: 4292

User input validation using TextBox_Validating event

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;
}

Upvotes: 1

Views: 325

Answers (1)

Neel
Neel

Reputation: 11721

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

Upvotes: 1

Related Questions