Monday, September 13, 2010

User Control vs. Custom Control in ASP.NET

ASP.NET provides two models of creating web controls  – user controls and custom controls.

In this article, we will discuss about following points.

1. What is User Control?
2. What is Custom Control?
3. What is the difference between User Control and Custom Control?
4. How to select appropriate Web Control out of two?

Go through the following explanation of all points.

1. What is User Control?
 
User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it. These are custom, reusable controls, and they use the same techniques that are employed by HTML and Web server controls. They offer an easy way to partition and reuse common user interfaces across ASP.NET Web applications. They use the same Web Forms programming model on which a Web Forms page works.

How to create a user control

The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only difference is that a user control does not include the <html>, <body>, and <form> elements since a Web Forms page hosts the user control. To create a user control, follow these steps:

• Open a text or HTML editor, and create a server-side code block exposing all the properties, methods, and events.
<script language="C#" runat="server">
public void button1_Click(object sender, EventArgs e)
{
          label1.Text = "Hello World!!!";
}
</script>
• Create a user interface for the user control.
<asp:Label id="label1" runat="server"/>
<br><br>
<asp:button id="button1" text="Hit" OnClick="button1_Click" runat="server" />

How to use a user control in a Web Forms page

• Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio .NET 2003, Microsoft Visual Studio 2005, or any text editor.

• Declare the @ Register directive. For example, use the following code.
<%@ Register TagPrefix="UC" TagName="TestControl" Src="test.ascx" %>
Note Assume that the user control and the Web Forms page are in the same location.

• To use the user control in the Web Forms page, use the following code after the @ Register directive.
<html>
<body>
<form runat="server">
<UC:TestControl id="Test1" runat="server"/>
</form>
</body>
</html>

How to create an instance of a user control programmatically in the code behind file of a Web Forms page

The previous example has instantiated a user control declaratively in a Web Forms page using the @ Register directive. However, you can instantiate a user control dynamically and add it to the page. Here are the steps for doing that:

1. Create a new Web Forms page in Visual Studio.

2. Navigate to the code behind file generated for this Web Forms page.

3. In the Page_Load event of the Page class, write the following code.

// Load the control by calling LoadControl on the page class.
Control c1 = LoadControl("test.ascx");

// add the loaded control in the page controls collection.
Page.Controls.Add(c1);
Note You can add a user control dynamically at certain events of the page life cycle.

How a user control is processed

When a page with a user control is requested, the following occurs:

• The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and generates a class that derives from the System.Web.UI.UserControl class.

• The parser then dynamically compiles the class into an assembly.

• If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for the user control, and the file is precompiled by the designer itself.

• Finally, the class for the user control, which is generated through the process of dynamic code generation and compilation, includes the code for the code behind file (.ascx.cs) as well as the code written inside the .ascx file.

2. What is Custom Control?

Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does.

How to choose the base class for your custom control

To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:

• You should derive from System.Web.UI.Control if you want the control to render nonvisual elements. For example, <meta> and <head> are examples of non-visual rendering.

• You should derive from System.Web.UI.WebControls.WebControl if you want the control to render HTML that generates a visual interface on the client computer.

If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class with these existing classes and can change their default behavior.

In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For example, you can use the WebControl class to control the look and styles through properties like font, color, and height.

How to create Custom Control

• Create Class Library project in Visual Studio.

• Add new class to your project called SimpleLabel, and derive SimpleLabel from the ‘System.Web.UI.Control’ class. It will create ‘SimpleLabel.ascx’ and ‘SimpleLabel.ascx.cs’ files.
public class SimpleLabel : Control {}

• Add some functionality to the class.
protected override void Render(HtmlTextWriter writer)
{
          writer.Write("Hello World from custom control");
}

• Compile the class library project. It will generate the DLL output.

• Open an existing or create a new ASP.NET Web application project.

• Add a Web Forms page where the custom control can be used.

• Add a reference to the class library in the references section of the ASP.NET project.

• Register the custom control on the Web Forms page.
<%@ Register TagPrefix="CC " Namespace=" CustomServerControlsLib " Assembly="CustomServerControlsLib " %>

• To instantiate or use the custom control on the Web Forms page, add the following line of code in the <form> tags.
<form id="Form1" method="post" runat="server">
<CC: SimpleLabel id="ctlSimpleControl" runat="server">
</CC: SimpleLabel >
</form>

• Run the Web Forms page, and you will see the output from the custom control.

3. What is the difference between User Control and Custom Control?
 
FactorsUser ControlCustom Control
CreationCreation is similar to the way Web Forms pages are created; well-suited for rapid application development (RAD)Writing involves lots of code because there is no designer support
ContentA much better choice when you need static content within a fixed layout, for example, when you make headers and footersMore suited for when an application requires dynamic content to be displayed; can be reused across an application, for example, for a data bound table control with dynamic rows
DesignWriting doesn't require much application designing because they are authored at design time and mostly contain static dataWriting from scratch requires a good understanding of the control's life cycle and the order in which events execute, which is normally taken care of in user controls
DeploymentDesigned for single-application scenarios

Deployed in the source form (.ascx) along with the source code of the application

If the same control needs to be used in more than one application, it introduces redundancy and maintenance problems
Designed so that it can be used by more than one application

Deployed either in the application's Bin directory or in the global assembly cache

Distributed easily and without problems associated with redundancy and maintenance
Locationwe have to use it within the application and it rests in the application directorywe can keep it in the Toolbox and use it whenever we want
 
4. How to select appropriate Web Control out of two?

The single most important factor is how the control will be used – will the control be application specific or generic and redistributable? If the control is application specific and contains a lot of static layout, such as a site header and footer, a user control would make sense. If the control is generic, redistributable, and contains dynamic layout, such as the server controls that ship with the .NET SDK, then a custom control would be more suitable.

Read more on my other blogs also:
Web Controls
Infix to Postfix Conversion
SharePoint 2010 Overview

No comments:

Post a Comment