Sunday 22 September 2013

Custom controls introduction, Creation and usage in asp.net project

A best friend of mine recently requested me to create a post for "Custom Controls creation and use in asp.net " with example and detailed explanation , so today I am going to talk a bit about custom controls which leads to a practical example of how to create a custom control and how to use it in your asp.net project.
First lets have little introduction of custom controls :
"Custom controls are individual assemblies, compiled into a dynamic link library (DLL) and used as any other ASP.Net server control", we can create them by :
  1.  deriving from the base control class ( today's example )
  2. driving from one existing control ( extending functionality of existing one )
  3.  combing two or more existing controls ( combination of more than one existing controls )
Today we have example of first type , we are going to create a custom label , the functionality of this label is that , when we set its text , it will validate if the assigned text is a valid email or not and change its color and append message as prefix like this in screen shot :


Now lets see how to create an asp.net custom control first :
  • Open visual studio , go to File->New->Project
  • Select Web projects and select Asp.net Server Control project
  • Name it , lets say CustomLabelControl
  • When you create project , you will have ServerControl1.cs class inherited from WebControl class, this is every thing for your custom control.
  • There will be a method " protected override void RenderContents( HtmlTextWriter output)", which is key , that is how your control will response to you visually , just copy and replace the following code with it :         

     protected override void RenderContents( HtmlTextWriter output)
            {
                  if (!String.IsNullOrEmpty(this.Text))
                    {
                            if (this.IsValidEmailAddress())
                              {
                                    output.Write("This is a valid email : ");
                                      output.Write("<FONT size=5 color=Blue>");
                                        output.Write("<B>");
                                          output.Write(Text);
                                            output.Write("</B>");
                                              output.Write("</FONT>");
                                            }
                                              else
                                                {
                                                      output.Write("This is not a valid email : ");
                                                        output.Write("<FONT size=5 color=red>");
                                                          output.Write("<B>");
                                                            output.Write(Text);
                                                              output.Write("</B>");
                                                                output.Write("</FONT>");
                                                              }
                                                            }
                                                              else
                                                                {

                                                                        output.Write("<FONT size=5 color=red>");
                                                                          output.Write("<B>");
                                                                            output.Write("Must enter something to validate!");
                                                                              output.Write("</B>");
                                                                                output.Write("</FONT>");
                                                                              }
                                                                            }

                                                                    It is using IsValidEmailAddress() method which can be defined in the same class as :


                                                                       protected bool IsValidEmailAddress( )
                                                                            {
                                                                                try
                                                                                {
                                                                                    // this is use for time saving, not optimal solution , but you can replace it with regular expression
                                                                                    MailAddress m = new MailAddress(this.Text);
                                                                                    return true;
                                                                                }
                                                                                catch (FormatException)
                                                                                {
                                                                                    return false;
                                                                                }
                                                                            }

                                                                    • And that's all , your custom control is ready to use , now build your project.
                                                                    Now second part starts from here , i.e how to use this control in your asp.net project, simple three step process :
                                                                    • Add reference of this control ( project dll ) to your asp.net project where you want to use it.
                                                                    • Register the control on the page where you want to use it , just directly below the @page directive like that :

                                                                    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CustomControlTest._Default" %>
                                                                    <%@ Register Assembly="CustomLabelControl"  Namespace="CustomLabelControl" TagPrefix="ccs" %>

                                                                    • Add control to your page like this :                                                                               <ccs:ServerControl1 runat="server" ID="ServerControl11" Text = "" />
                                                                    • Now just set the text of this control , behind any event , lets say on button click,                     protected void Button1_Click(object sender, EventArgs e)

                                                                              {
                                                                                    this.ServerControl11.Text = this.TextBox1.Text;
                                                                                  }

                                                                          And this control will be automatically say if this is a proper email address or not.
                                                                          Sample solution project with custom control project and its use in asp.net project is attached here :    CustomControl Project.

                                                                          No comments:

                                                                          Post a Comment