Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET custom controls


May 13, 2021 ASP.NET


Table of contents


Custom controls

ASP.NET allows the user to create controls. T hese user-defined controls are classified as:

  • The user control
  • Custom controls

The user control

User controls behave like ASP.NET pages or web page forms, and can be used by many other pages. T hese are derived from the System.Web.UI.UserControl class. T hese controls have the following characteristics:

  • They have .ascx extensions.
  • They may not contain any, or labels.
  • They have a Control instruction instead of a Page instruction.

To understand this concept, let's create a simple user control that will be used as a footer for a web page. T o create and use user controls, take the following steps:

  • Create a new web application.
  • Right-click the item folder on Solution Explorer and select ADD New Item.

ASP.NET custom controls

  • Select Web User Control from the Add New Item dialog box and name it footer.ascx. I nitially, footer.ascx contained only one Control instruction.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="footer.ascx.cs" 
   Inherits="customcontroldemo.footer" %>
  • Add the following code to the file:
<table>
   <tr>
      <td align="center"> Copyright ©2010 TutorialPoints Ltd.</td>
   </tr>

   <tr>
      <td align="center"> Location: Hyderabad, A.P </td>
   </tr>
</table>

To add user controls to your web page, you must add a Register directive and an instance of a page user control. T he following code shows the instructions:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="customcontroldemo._Default" %>

<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

   <head runat="server">
      <title>
         Untitled Page
      </title>
   </head>

   <body>

      <form id="form1" runat="server">
         <div>

            <asp:Label ID="Label1" runat="server" Text="Welcome to ASP.Net Tutorials "></asp:Label>
            <br />  <br />
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click"  Text="Copyright Info" />

         </div>
         <Tfooter:footer ID="footer1" runat="server" />
      </form>

   </body>
</html>

When executed, the page displays the footer and this control can be used on all pages of your site.

ASP.NET custom controls

Observe the following:

(1) T he Register directive specifies a label name and label prefix for the control.

<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>

(2) The following label names and prefixes should be used when adding user controls to the page:

<Tfooter:footer ID="footer1" runat="server" />

Custom controls

Custom controls are deployed as separate collections. T hey are compiled into a Dynamic Link Library (DLL) and used as ASP.NET any other service control. T hey can be created by any of the following methods:

  • By obtaining a custom control from an existing control.
  • Form a new custom control by combining two or more existing controls.
  • By obtaining from the basic control class.

To understand this concept, let's create a custom class that simply renders a text message on the browser. T o create a control, take the following steps:

Create a new website. R ight-click Solution (not an item) at the top of the tree in Solution Explorer.

ASP.NET custom controls

In the New Project dialog box, select Server Control from the ASP.NET template.

ASP.NET custom controls

The steps above add a new project and create a complete custom control for solution called ServerControl1. I n this example, let me name the CustomControls project. I n order to use this control, it must be added to the page as a reference before it can be registered on the page. T o add a reference to an existing project, right-click the project (not solution) and click Add Reference.

Select the CustomControl project from the Projects tab in the Add Reference dialog box. Solution Explorer can display references.

ASP.NET custom controls

In order to use the control on the page, @Page the Register directive under the directive.

<%@ Register Assembly="CustomControls"  Namespace="CustomControls"  TagPrefix="ccs" %>

Also, you can use controls that are similar to any other control.

<form id="form1" runat="server">
   <div>
      <ccs:ServerControl1 runat="server" Text = "I am a Custom Server Control" />
   </div> 
</form>

When executed, the Control's Text property is displayed on the browser as follows:

ASP.NET custom controls

Use custom classes

In the previous example, the Text property value of the custom class was set. W hen the control is created, the ASP.NET added by default. T he following controls are revealed by the code behind the file.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
   [DefaultProperty("Text")]
   [ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]

   public class ServerControl1 : WebControl
   {
      [Bindable(true)]
      [Category("Appearance")]
      [DefaultValue("")]
      [Localizable(true)]

      public string Text
      {
         get
         {
            String s = (String)ViewState["Text"];
            return ((s == null) ? "[" + this.ID + "]" : s);
         }

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

      protected override void RenderContents(HtmlTextWriter output)
      {
         output.Write(Text);
      }
   }
}

The above code is automatically generated into a custom control. E vents and methods can be added to the custom control class.

Example

Let's extend the previous custom control called ServerControl1. L et's give it a method called checkpalindrome, which will give it permission to check palindrome.

Palindrome is the same text/literal value that is still spelled when reversed. F or example, Malayalam, madam, saras, etc.

Extend the code for the custom control, which should look like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
   [DefaultProperty("Text")]
   [ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1  >")]

   public class ServerControl1 : WebControl
   {
      [Bindable(true)]
      [Category("Appearance")]
      [DefaultValue("")]
      [Localizable(true)]

      public string Text
      {
         get
         {
            String s = (String)ViewState["Text"];
            return ((s == null) ? "[" + this.ID + "]" : s);
         }

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

      protected override void RenderContents(HtmlTextWriter output)
      {
         if (this.checkpanlindrome())
         {
            output.Write("This is a palindrome: <br />");
            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 palindrome: <br />");
            output.Write("<FONT size=5 color=red>");
            output.Write("<B>");
            output.Write(Text);
            output.Write("</B>");
            output.Write("</FONT>");
         }
      }

      protected bool checkpanlindrome()
      {
         if (this.Text != null)
         {
            String str = this.Text;
            String strtoupper = Text.ToUpper();
            char[] rev = strtoupper.ToCharArray();
            Array.Reverse(rev);
            String strrev = new String(rev);

            if (strtoupper == strrev)
            {
               return true;
            }
            else
            {
               return false;
            }
         }
         else
         {
            return false;
         }
      }
   }
}

When you change the code for the space, you have to build the method by clicking Build --gt; Build Solution so that the changes can be reflected in your project. A dd a text box and a button control to the page so that the user can provide a piece of text. W hen button is clicked, it is used to check the palindrome.

<form id="form1" runat="server">
   <div>
      Enter a word:
      <br />
      <asp:TextBox ID="TextBox1" runat="server" style="width:198px"> </asp:TextBox>

      <br /> <br />

      <asp:Button ID="Button1" runat="server onclick="Button1_Click" Text="Check Palindrome" style="width:132px" />

      <br /> <br />

      <ccs:ServerControl1 ID="ServerControl11" runat="server" Text = "" />
   </div>
</form>

Button's Click event handle simply copies text from the text box into the text property of the custom control.

protected void Button1_Click(object sender, EventArgs e)
{
   this.ServerControl11.Text = this.TextBox1.Text;
}

When executed, the control successfully detects palindromes.

ASP.NET custom controls

Observe the following:

(1) When you add a reference to a custom control, it is added to the toolbox and you can use it directly from the toolbox just like any other control.

ASP.NET custom controls

(2) The RenderContents method of the custom control class is overwritten and you can add your own methods and events.

(3) The RenderContents method uses htmlTextWriter parameters, which will be responsible for displaying on the browser.