Reputation: 9021
I have created a number of custom user controls in my application. They are controls which validate their own content using a Validates() method. When I click a button on the form, I would like to call this method on any control which has the method. What is the best way to achieve this?
I'm able to identify and the controls and check if they have the method, but unsure how to call it at this point. (All the controls begin with 'cc')
foreach (Control c in this.Controls)
{
if (c.Name.Length > 2 && c.Name.Substring(0, 2).Equals("cc"))
{
var type = c.GetType();
if (type.GetMethod("Validates") != null)
{
// Call method here
}
}
}
Can anyone point me in the right direction, or perhaps a better way I can do this. I expect these controls will be on a lot of forms so i'd like to make a grouped validation as easy as possible from the parent form.
Thanks,
Upvotes: 0
Views: 606
Reputation: 13150
You should create an interface
and every control having Validate
method should implement that interface.
public interface IValidatable
{
void Validates();
}
and check the interface in the loop.
foreach (Control c in this.Controls)
{
IValidatable validateControl = c as IValidatable;
if(validateControl != null)
{
// do the validation.
validateControl.Validates();
}
Upvotes: 0
Reputation: 16393
The usual way to do it in WinForms is to use the Form Validating events.
Upvotes: 1
Reputation: 5530
Perhaps try to use an Interface
public interface IValidateMyData
{
bool Validate();
}
public class ValidationControl : Control, IValidateMyData
{
// code here
public bool Validate()
{
return true;
}
}
In your Form iterate over all controls like above but don't check on the name but determine if the control implements the IValidateMyData Interface:
foreach (Control c in this.Controls)
{
if ( c is IValidateMyData )
{
var validationResult = (c as IValidateMyData).Validate();
}
}
with this method your controls are not bound to have a specific name prefix.
furthermore you can move the iteration over all controls the validation to a baseclass which your form inherits from and just call the "ValidateAllControls()" Method in your form.
Upvotes: 1