h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Validation TextBox with Error Provider in C#.Net

HI All,
    Today, We discussed about TextBox Validation with Error Provider in C#.Net


using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;
 using System.Text.RegularExpressions;
 namespace LaksUserControl.UtilityLayer
{
 class NCharacterTextBox :TextBox
 {
 CustomErrorProvider objCEP = new CustomErrorProvider();
 public enum CheckStatus { True, False, };
 public enum CheckStatusBlank { True, False, };
 public enum ValidatieonType { BLANK, CHARACTER, BLANKWITHCHARACTER, };
 private CheckStatus m_CheckStatus;
 private CheckStatusBlank m_CheckStatusBlank;

public CheckStatus CheckErrorProvider
 {
 get { return m_CheckStatus; } set { m_CheckStatus =value; }
 }
 public CheckStatusBlank CheckEmptyBox { get { return m_CheckStatusBlank; } set { m_CheckStatusBlank = value; }
 }
 private bool ValidateAlphabet(string str)
 {
 Regex regexAlphaNum = new Regex(@"^[a-zA-Z]*$"); return regexAlphaNum.IsMatch(str);
}
 bool checkBlank;
 private bool CheckBlankTextBox(ValidatieonType Mode)
 {
 switch (Mode)
 {
 case ValidatieonType.BLANK:
 if (string.IsNullOrEmpty(this.Text))
 checkBlank= true;
 else checkBlank=false;
 break;
 case ValidatieonType.CHARACTER:
 if (!ValidateAlphabet(this.Text))
 checkBlank=true;
 else
 checkBlank=false;
 break;
 case ValidatieonType.BLANKWITHCHARACTER:
 if (string.IsNullOrEmpty(this.Text) | !ValidateAlphabet(this.Text))
 checkBlank=true;
 else
 checkBlank=false;
 break;
 }
 return checkBlank;
 }
 bool chkdisplayEP;
 protected internal bool DisplayErrorProvider(string CheckErrorProvider, string CheckEmptyBox, string Message)
 {
 if (CheckErrorProvider == "true" && CheckEmptyBox == "true")
 {
 if (CheckBlankTextBox(ValidatieonType.BLANKWITHCHARACTER))
 {
 objCEP.SetError(this, Message);
 chkdisplayEP=true;
 }
 else
 {
 objCEP.SetError(this, "");
 chkdisplayEP=false;
 }
 }
 else if ((CheckErrorProvider == "true" && CheckEmptyBox == "false"))
 {
 if (CheckBlankTextBox(ValidatieonType.CHARACTER))
 {
 objCEP.SetError(this, Message);
 chkdisplayEP = true;
 }
 else
 {
 objCEP.SetError(this, "");
 chkdisplayEP = false;
 }
 }
 return chkdisplayEP;
 }
 }
 }

Error Provider
using System;
using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;
 namespace LaksUserControl.UtilityLayer
 {
 class CustomErrorProvider : ErrorProvider
 {
 public List GetControls()
 {
 return this.GetControls(this.ContainerControl); 
 }
 public List GetControls(Control ParentControl)
 { 
 List ret = new List();
 if (!string.IsNullOrEmpty(this.GetError(ParentControl))) ret.Add(ParentControl);
 foreach (Control c in ParentControl.Controls) 
 {
 List child = GetControls(c); if (child.Count > 0) ret.AddRange(child); } return ret;
 }
 }
 }