To handle validation do one of these:
- Validate with a method inside the user control
Have your user control have a delegate
property (e.g. ValidationHandler
) that can handle the validation (this would allow you to have a class with a bunch of validators that you could assign to your controls)
public delegate void Validator(...)
public Validator ValidationHandler { get; set; }
Have your user control generate a validation request event
(e.g. ValidationRequested
)
public event EventHandler<ValidationEventArgs> ValidationRequested
To notify the system that an error has occurred do one of these:
Use an event
that interested parties can subscribe to (e.g. ValidationFailed
)
If the object that performs the validation (via the delegate
or event
) is also the one that you want to generate the error message from, it can raise the error message itself.
EDIT:
Since you've said you would validate inside your control, the code for a ValidationFailed event might look like:
// In your user control
public class ValidationFailedEventArgs : EventArgs
{
public ValidationFailedEventArgs(string message)
{
this.Message = message;
}
public string Message { get; set; }
}
private EventHandler<ValidationFailedEventArgs> _validationFailed;
public event EventHandler<ValidationFailedEventArgs> ValidationFailed
{
add { _validationFailed += value; }
remove { _validationFailed -= value; }
}
protected void OnValidationFailed(ValidationFailedEventArgs e)
{
if(_validationFailed != null)
_validationFailed(this, e);
}
private void YourValidator()
{
if(!valid)
{
ValidationFailedEventArgs args =
new ValidationFailedEventArgs("Your Message");
OnValidationFailed(args);
}
}
// In your main form:
userControl.ValidationFailed +=
new EventHandler<ValidationFailedEventArgs>(userControl_ValidationFailed);
// ...
private void userControl_ValidationFailed(object sender,
ValidationFailedEventArgs e)
{
statusBar.Text = e.Message;
}