0
votes

I am trying to validate textboxes for empty values. If the textbox is empty and loses focus, an error has to show and the textbox has to receive focus again.

Reading about this I came across the Validating event, which can be cancelled through e.Cancel. However when I try to do this, I get an error message.

My code:

private void CheckInput(CancelEventArgs e, TextBox tb)
{
   ErrorProvider error = new ErrorProvider();
   if (!string.IsNullOrEmpty(tb.Text))
   {
      error.SetError(tb, "*");
      e.Cancel = true;
   }

   else
   {
      error.SetError(tb, "");
   }
}

private void tbTitel_Validated(object sender, CancelEventArgs e)
{
    CheckInput(e, tbTitel);

}

And the error I get is the following:

Error 1 No overload for 'tbTitel_Validated' matches delegate 'System.EventHandler'

How can I fix this?

4

4 Answers

4
votes

The validating uses this delegate:

private void tbTitel_Validating(object sender, CancelEventArgs e)
{
}

The validated event uses this:

private void tbTitel_Validated(object sender, EventArgs e)
{
}  

You want to use the Validating event (you should link you eventhandler to the validating event, not the validated event. This way you can cancel it.

You probably clicked the validating first and copy/paste/selected the eventhandler name into the validated event. (designer)

1
votes

The error occurs, because tbTitel_Validated doesnt have CancelEventArgs in its signature.

Take a look at this thread for further information: No overload for 'method' matches delegate 'System.EventHandler'

Conclusion: Use tbTitel_Validating instead.

1
votes

You should use the Validating event to execute your checks, not the Validated event.

The two events have different signatures. The Validated event receives the simple EventArgs argument, while the Validating event receives the CancelEventArgs argument that could be used to revert the focus switch.

Said that, it seems that your logic is wrong.

// error if string is null or empty
// if (!string.IsNullOrEmpty(tb.Text))
if (string.IsNullOrEmpty(tb.Text))
{
   error.SetError(tb, "*");
   e.Cancel = true;
}
else
{
   error.SetError(tb, "");
}
0
votes

Alwasy use validation statements at Object.Validated event handler

Likewise:


 private void textBox1_Validated(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text == "")
            {
                MessageBox.Show("Please use valid data input!!");
            }
        }