1、创建验证类
using System;
using System.Windows.Forms;
using System.Reflection;
using System.ComponentModel;
namespace Com.Jesus.Utility
{
public class ValidationHelper
{
public static bool hasValidationErrors(System.Windows.Forms.Control.ControlCollection controls)
{
bool hasError = false;
// Now we need to loop through the controls and deterime if any of them have errors
foreach (Control control in controls)
{
// check the control and see what it returns
bool validControl = IsValid(control);
// If it's not valid then set the flag and keep going. We want to get through all
// the validators so they will display on the screen if errorProviders were used.
if (!validControl)
hasError = true;
// If its a container control then it may have children that need to be checked
if (control.HasChildren)
{
if (hasValidationErrors(control.Controls))
hasError = true;
}
} return hasError;
}
// Here, let's determine if the control has a validating method attached to it
// and if it does, let's execute it and return the result
private static bool IsValid(object eventSource)
{
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)
{
EventHandlerList 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;
CancelEventArgs eventArgs = new CancelEventArgs();
eventArgs.Cancel = false;
object[] 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
if (eventArgs.Cancel)
return false;
else
return true;
}
}
}
}
targetType = targetType.BaseType;
}
while (targetType != null); return true;
}
}
}
2、设置每个要验证的控件Validating事件。注意:当验证失败时确保e.Cancel
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if ((sender as TextBox).Text.Trim() == String.Empty)
{
errorProvider1.SetError((sender as TextBox), "Last Name is Required");
e.Cancel = true;
}
else
errorProvider1.SetError((sender as TextBox), "");
}
3、设置Form的AutoValidate值为EnableAllowFocusChange
4、添加提交按钮事件
private void btnSubmit_Click(object sender, EventArgs e)
{
// the controls collection can be the whole form or just a panel or group
if (Com.Jesus.Utility.ValidationHelper .hasValidationErrors(this.Controls))
return;
// if we get here the validation passed
this.Close();
}
从国外网站拷来略作改动,测试好用。现在发现国外网站还是能解决问题的,国内的抄袭风过于严重了,一搜都是一样的。