0

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 Answers 4

4

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)

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

Comments

1

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.

Comments

1

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, "");
}

1 Comment

Thanks. That was indeed the problem. I do however have other problems now but I will try to fix them as go. :)
0

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!!");
            }
        }

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.