Click here to Skip to main content
15,895,870 members
Articles / Programming Languages / C#

Custom Web Controls Lib

Rate me:
Please Sign up or sign in to vote.
4.33/5 (7 votes)
21 May 2009CPOL 27.5K   144   19   6
Custom Web Controls Lib
Image 1

Introduction

This library contains four custom controls. Each control has the validations for the required character type:

  1. NumericTextBox

    This control validates on keypress the entered char and it accepts only numbers.

  2. DecimalTextBox

    This control validates on keypress the entered char and it accepts only Decimal.

  3. StringTextBox

    This control validates on keypress the entered char and it accepts alpha pluse. According to its property AllowSpace and AllowDigit it will accept the digit and space.

  4. CustomTextBox

    This control has type property and according to it in validate the validation will occur before submit.

Using the Code

After dragging the control on the page, just set controls properties:

XML
<cc1:StringTextBox ID="StringTextBox1"  
	runat="server" AllowDigit="true" AllowSpace="true">
cc1:CustomTextBox ID="CustomTextBox6"
  runat="server" TextType="AlphaWithSpace" InvalidRequiredMessage="*" >

All these controls have common properties which are included in BaseCustomControl, InvalidRequiredMessage, EnableClientScript, IsRequired, CssClassTxt, CssClassErr.

Source Code

1- BaseCustomControl

C#
   public class BaseCustomControl : TextBox
    {
   public string InvalidRequiredMessage
        {
            get
            {
 string s = "Required";
 object obj = ViewState["InvalidRequiredMessage"];
 if (obj != null)
 {
     s = (string)obj;

 }
 return s;
            }

            set
            {
 ViewState["InvalidRequiredMessage"] = value;
            }
        }
       public bool EnableClientScript
        {
            get
            {
 bool b = true;
 object obj = ViewState["EnableClientScript"];
 if (obj != null)
 {
     b = (bool)obj;

 }
 return b;
            }

            set
            {
 ViewState["EnableClientScript"] = value;
            }
        }
        public bool IsRequired
        {
            get
            {
 bool b = true;
 object obj = ViewState["IsRequired"];
 if (obj != null)
 {
     b = (bool)obj;

 }
 return b;
            }

            set
            {
 ViewState["IsRequired"] = value;
            }
        }
        public string CssClassTxt
        {
            get
            {
 string s = "txtCls";
 object obj = ViewState["CssClassTxt"];
 if (obj != null)
 {
     s = (string)obj;

 }
 return s;
            }

            set
            {
 ViewState["CssClassTxt"] = value;
 this.CssClass = value;
            }
        }
        public string CssClassErr
        {
            get
            {
 string s = "errCls";
 object obj = ViewState["CssClassErr"];
 if (obj != null)
 {
     s = (string)obj;

 }
 return s;
            }

            set
            {
 ViewState["CssClassErr"] = value;

            }
        }
        protected override void OnInit(EventArgs e)
        {
                      //check Required
            if (IsRequired)
            {
 req = new RequiredFieldValidator();
 req.ControlToValidate = this.ID;
 req.ErrorMessage = this.InvalidRequiredMessage;
 req.EnableClientScript = this.EnableClientScript;
 req.Display = ValidatorDisplay.Dynamic;
              
 req.CssClass = CssClassErr;
 Controls.Add(req);
            }
            CssClass = CssClassTxt;
       }
   protected override void Render(HtmlTextWriter output)
        {
base.Render(output);

 if (req != null)
 {
     req.RenderControl(output);
 }
    }
}

2- CustomTextBox

C#
   public enum TextBoxType
   {
       Text = 1,
       AlphaWithSpace = 2,
       AlphaOnly=3,
       Numeric=4,
       Email = 5,
       URL=6
   }

  public class CustomTextBox : BaseCustomControl
   {
       public string InvalidDataMessage
       {
           get
           {
string s = "Invalid Data";
object obj = ViewState["InvalidDataMessage"];
if (obj != null)
{
    s = (string)obj;

}
return s;
           }

           set
           {
ViewState["InvalidDataMessage"] = value;
           }
       }

       public TextBoxType TextType
       {
           get
           {
TextBoxType t = TextBoxType.AlphaOnly;
object obj = ViewState["TextType"];
if (obj != null)
{
    t = (TextBoxType)obj;

}
return t;
           }

           set
           {
ViewState["TextType"] = value;
           }
      protected override void OnInit(EventArgs e)
       {
           base.OnInit(e);
           reg = new RegularExpressionValidator();
           reg.ControlToValidate = this.ID;
           reg.ErrorMessage = this.InvalidDataMessage;
           reg.EnableClientScript = this.EnableClientScript;
           reg.Display = ValidatorDisplay.Dynamic;
           //check Type
           switch (TextType)
           {

case TextBoxType.AlphaOnly:
    {
        reg.ValidationExpression = @"[a-zA-Z]*";
        break;
    }
case TextBoxType.Numeric:
    {
        reg.ValidationExpression = @"[0-9]*";
        break;
    }

case TextBoxType.AlphaWithSpace:
    {
        reg.ValidationExpression = @"[a-zA-Z ]*";
        break;
    }
case TextBoxType.Text:
    {
        reg.ValidationExpression = @"[\w^\w\W^\W]*";
        break;
    }
case TextBoxType.Email:
    {
        reg.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
        break;
    }

     case TextBoxType.URL:
    {
        reg.ValidationExpression = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
        break;
    }
          }

           Controls.Add(reg);
           #endregion
       }

       protected override void Render(HtmlTextWriter w)
       {
base.Render(w);
if (reg != null)
{
    reg.RenderControl(w);
}
       }

3- DecimalTextBox

C#
    public class DecimalTextBox : BaseCustomControl
    {
        protected override void OnInit(EventArgs e)
        {
            this.Attributes.Add("onkeypress", "javascript: return AllowDecimal
					(event,'"+this.ClientID+"');");
            base.OnInit(e);
        }
        protected override void  OnPreRender(EventArgs e)
{f(!this.Page.ClientScript.IsClientScriptBlockRegistered("strAllowNumeric"))
 {
     string script = @"function AllowDecimal(e,txt)
     {
         var iKeyCode = 0;
         if (window.event)
         {
         iKeyCode = window.event.keyCode
         }
         else if (e)
         {
         iKeyCode = e.which;
         }
         var y = document.getElementById(txt).value;
         if(iKeyCode==46 && y.indexOf('.')==-1){ return true;}
         else if ((iKeyCode > 47 && iKeyCode < 58)|| iKeyCode==8)
         { return true;}
         else
         {return false;} };
this.Page.ClientScript.RegisterClientScriptBlock
	(this.Page.GetType(), "strAllowDecimal", script,true);
 }
 base.OnPreRender(e);
            }
    }
}

4- NumericTextBox

C#
    public class NumericTextBox : BaseCustomControl
    {
        protected override void OnInit(EventArgs e)
        {             
             this.Attributes.Add("onkeypress", 
				"javascript: return AllowNumeric(event);");
            base.OnInit(e); 

        protected override void  OnPreRender(EventArgs e)
{if(!this.Page.ClientScript.IsClientScriptBlockRegistered("strAllowNumeric"))
 {
      string script = "function AllowNumeric(e)";
       script += "{";
       script += "var iKeyCode = 0;";
       script += "if (window.event)";
       script += "{iKeyCode = window.event.keyCode}";
       script += "else if (e)";
       script += "{iKeyCode = e.which;}";
       script += "if ((iKeyCode > 47 && iKeyCode < 58) || 
				iKeyCode == 8||iKeyCode == 0)";
       script += "{ return true}";
       script += "else";
       script += "{return false;}";
       script += "}";
this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), 
					"strAllowNumeric", script,true);    
 }

 base.OnPreRender(e);

            }
            catch (Exception ex)
            {

 throw ex;
            }
        }

        #endregion
    }
}

5- StringTextBox

C#
    public class StringTextBox : BaseCustomControl
    {
        public bool AllowAlpha
        {
            get
            {
 bool b = true;
 object obj = ViewState["AllowAlpha"];
 if (obj != null)
 {
     b = (bool)obj;

 }
 return b;
            }

            set
            {
 ViewState["AllowAlpha"] = value;
            }
        }

public bool AllowSpace
        {
            get
            {
 bool b = false;
 object obj = ViewState["AllowSpace"];
 if (obj != null)
 {
     b = (bool)obj;

 }
 return b;
            }

            set
            {
 ViewState["AllowSpace"] = value;
            }
        }

        public bool AllowDigit
        {
            get
            {
 bool b = false;
 object obj = ViewState["AllowDigit"];
 if (obj != null)
 {
     b = (bool)obj;

 }
 return b;
            }

            set
            {
 ViewState["AllowDigit"] = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if ((!AllowAlpha) && AllowDigit)
            {
 this.Attributes.Add("onkeypress", "javascript: return AllowDigit
			(event," + AllowSpace.ToString().ToLower() + ");");
            }
            else if (AllowAlpha)
            {
 this.Attributes.Add("onkeypress", "javascript: return AllowAlpha
	(event," + AllowSpace.ToString().ToLower() + "," + 
	AllowDigit.ToString().ToLower() + ");");

            }
            else
            {
 this.Enabled = false;
            }
        protected override void OnPreRender(EventArgs e)
        {
string script1="<script language="javascript">";
 script1+="function AllowAlpha(e,allowSpace,allowDigit)";
 script1+="{";

 script1+="var KeyID = (window.event) ? event.keyCode : e.which;";
 script1+="if((KeyID >= 65 && KeyID <= 90)";
 script1+="|| (KeyID >= 97 && KeyID <= 122)";
 script1+="|| (KeyID >= 33 && KeyID <= 47)";
 script1+="||(KeyID >= 58 && KeyID <= 64)";
 script1+="|| (KeyID >= 91 && KeyID <= 96)";
 script1+="|| (KeyID ==32 && allowSpace)";
 script1+="|| (KeyID > 47 && KeyID < 58 && allowDigit)";
 script1+="|| (KeyID >= 123 && KeyID <= 126))";
 script1+="{return true;}";
 script1+="else";
 script1+="{return false;}";
 script1+="}";
 script1+="</script>";
 this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), 
					"strAllowAlpha", script1);
 if ((!AllowAlpha) && AllowDigit)
 {
    string script="<script language="javascript">";
    script+="function AllowDigit(e,allowSpace)";
    script+="{";
    script+="var iKeyCode = 0;";
    script+="if (window.event)";
    script+="{iKeyCode = window.event.keyCode}";
    script+="else if (e)";
    script+="{iKeyCode = e.which;}";
    script+="if ((iKeyCode > 47 && iKeyCode < 58)";
    script+="|| (iKeyCode ==32 && allowSpace))";
    script+="{ return true}";
    script+="else";
    script+="{return false;}";
    script+="}";
    script += "</script>";
    this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), 
					"strAllowDigit", script);
 }
  base.OnPreRender(e);
            }

History

  • 22nd May, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Egypt Egypt
I am experienced in web development with Microsoft technologies using ASP.NET Core ,C#, ASP.NET MVC, ASP.NET Web Api, ADO.NET ,LINQ, web services. I have a working experience with Model View Controller (MVC), and have been involved in maintaining versions of source code using TFS (Team Foundation Server) 2010. I have also developed web user controls, master pages, validation controls, CSS files using technologies like AJAX Toolkit, JQuery, JavaScript, Telerik UI controls, XML, HTML ,angular 1.4., angular 2 , typescript, SPA single page application.

Comments and Discussions

 
GeneralVery good Pin
Yves18-Jan-10 14:45
Yves18-Jan-10 14:45 
GeneralRe: Very good Pin
Nesreen Maged12-Feb-10 0:30
Nesreen Maged12-Feb-10 0:30 
StringTextBox is a class

StringTextBox1 is an object of StringTextBox class
GeneralEmbedded Resources Pin
ahmednabil27-May-09 2:14
ahmednabil27-May-09 2:14 
GeneralRe: Embedded Resources Pin
Nesreen Maged27-May-09 6:03
Nesreen Maged27-May-09 6:03 
GeneralVery good indeed. Pin
adatapost23-May-09 22:10
adatapost23-May-09 22:10 
GeneralRe: Very good indeed. Pin
Nesreen Maged25-May-09 10:50
Nesreen Maged25-May-09 10:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.