ASP.NET allows users to create controls. These user-defined controls are classified as:
user control
Custom controls
User controls behave like miniature ASP.NET pages or web forms that can be used by many other pages. These are derived from the System.Web.UI.UserControl class. These controls have the following properties:
They have the .ascx extension.
They may not contain any, or tags.
They have a Control directive instead of a Page directive.
To understand this concept, let's create a simple user control that will serve as the footer of a web page. In order to create and use user controls, take the following steps:
Create a new web application.
Right-click the project folder in Solution Explorer and select ADD New Item.
Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially, footer.ascx contains only a Control directive.
<%@ 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, AP </td> </ tr></table>
To add a user control to your web page, you must add a Register directive and an instance of the page user control. The 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 footer is displayed and the control is available on all pages on your site.
Observe the following:
(1) The Register command specifies a label name and label prefix for the control.
<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>
(2) The following tag names and prefixes should be used when adding user controls on the page:
<Tfooter:footer ID="footer1" runat="server" />
Custom controls are deployed as separate collections. They are compiled into dynamic link libraries (DLL) and used as any other ASP.NET service control. They can be created by any of the following methods:
By getting a custom control from an existing control.
Create a new custom control by combining two or more existing controls.
By getting it from the base control class.
To understand this concept, let's create a custom class that will simply render a text message on the browser. In order to create the control, take the following steps:
Create a new website. Right-click the solution (not the project) at the top of the tree in Solution Explorer.
In the New Project dialog box, select ASP.NET Server Control from the project template.
The above steps add a new project and create a complete custom control for the solution called ServerControl1. In this example, let me name the CustomControls project. In order to use this control, it must be added as a reference to the web page before being registered on the page. To add a reference to an existing project, right-click on the project (not the solution) and click Add Reference.
Select the CustomControl project from the Projects tab in the Add Reference dialog box. Solution Explorer can display references.
To use the control on the page, add a Register directive under the @Page directive.
<%@ Register Assembly="CustomControls" Namespace="CustomControls" TagPrefix="ccs" %>
Moreover, you can use controls like 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 shown below:
In the previous example, the Text property value of the custom class was set. ASP.NET adds this property by default when the control is created. The following code after the control's file reveals 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) { output.Write(Text); } }}
The above code is automatically generated for a custom control. Events and methods can be added to custom control classes.
Let's extend the previous custom control named ServerControl1. Let's give it a method called checkpalindrome which will give it permission to check the palindrome.
Palindrome is a word/literal value that still spells the same when reversed. For example, Malayalam, madam, saras etc.
Extend the code for your custom control and it 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 of a space, you must build the method by clicking Build --> Build Solution so that the changes can be reflected in your project. Add a text box and a button control to the page so that the user can provide a piece of text. When the 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"> </asp:TextBox> <br /> < br /> <asp:Button ID="Button1" runat="server onclick="Button1_Click" Text="Check Palindrome" /> <br /> <br /> <ccs:ServerControl1 ID="ServerControl11" runat="server" Text = "" /> </div></form>
The button's Click event handler simply copies the text in the text box to the custom control's text property.
protected void Button1_Click(object sender, EventArgs e){ this.ServerControl11.Text = this.TextBox1.Text;}
When executed, the control successfully detects palindromes.
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 like other controls.
(2) The RenderContents method of the custom control class has been overridden, and you can add your own methods and events.
(3) The RenderContents method takes a HtmlTextWriter type parameter, which will be responsible for displaying it on the browser.