C# Winform 窗体控件验证

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();
        }

从国外网站拷来略作改动,测试好用。现在发现国外网站还是能解决问题的,国内的抄袭风过于严重了,一搜都是一样的。

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值