private static bool IsValid(object eventSource, Dictionary<Control, List<string>> errors )
{
bool isValid = true;
const string name = "EventValidating";
Type targetType = eventSource.GetType();
do
{
FieldInfo[] fields = targetType.GetFields(
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic);
foreach (FieldInfo field in fields)
{
if (field.Name == name)
{
var eventHandlers = ((EventHandlerList) (eventSource.GetType().GetProperty("Events",
(BindingFlags
.FlattenHierarchy |
(BindingFlags
.NonPublic |
BindingFlags
.Instance)))
.GetValue(eventSource, null)));
Delegate d = eventHandlers[field.GetValue(eventSource)];
if ((!(d == null)))
{
Delegate[] subscribers = d.GetInvocationList();
// ok we found the validation event, let's get the event method and call it
foreach (Delegate d1 in subscribers)
{
// create the parameters
object sender = eventSource;
var eventArgs = new CancelEventArgs();
eventArgs.Cancel = false;
var parameters = new object[2];
parameters[0] = sender;
parameters[1] = eventArgs;
// call the method
d1.DynamicInvoke(parameters);
// if the validation failed we need to return that failure
isValid &= !eventArgs.Cancel;
if (!isValid)
{
List<string> eee = new List<string>();
Control ctr = eventSource as Control;
if (ctr != null)
{
PropertyInfo pi = d1.Target.GetType().GetProperty("ErrorMessage");
if (pi != null)
{
if (!errors.ContainsKey(ctr))
errors.Add(ctr, eee);
else
eee = errors[ctr];
string val = (string)pi.GetValue(d1.Target, null);
eee.Add( val );
}
}
int i = 0;
}
//if (eventArgs.Cancel)
// return false;
//return true;
}
}
}
}
targetType = targetType.BaseType;
} while (targetType != null);
return isValid;
}