There are many controls in Microsoft Visual Studio 2005 that certainly save you lots of development time, but there are always opportunities for you to build your own controls to save even more development time. Many business problems require custom controls to simplify the development solution. Custom controls are typically required to obtain different functionality, new functionality, or the combined functionality of several controls.

There are many controls in Microsoft Visual Studio 2005 that certainly save you lots of development time, but there are always opportunities for you to build your own controls to save even more development time. Many business problems require custom controls to simplify the development solution. Custom controls are typically required to obtain different functionality, new functionality, or the combined functionality of several controls.

Custom Web Control Types

There are three primary custom control types that will be covered in this chapter: user controls, custom Web controls, and composite controls. The following is a description of these controls:

 ¦ User control
A user control is a template control that provides extra behavior to allow constituent (individual) controls to be added to the user control in the Graphical User Interface (GUI) designer. These controls are added to the user control’s template file, the .ascx file. The .ascx file is similar to the Web page’s .aspx file and can have a code-behind page. To enable reuse, the .ascx and code-behind files must be included in each project that requires the user control.
 
¦ Custom Web control
A custom Web control is a control that inherits from a Web control, where you either write all of the code to render the control, or inherit it from an existing Web control and provide extra behavior as necessary. The class file can be compiled to a .dll that can be shared among applications and can optionally be installed in the global assembly cache (GAC).

¦ Composite control
 A composite control is a custom Web control that can contain constituent controls; the constituent controls are added to the composite control
via code to the class file that defines the control. The class file can be compiled
to a .dll that can be shared among applications and can optionally be installed in the GAC.

In this article I will cover only user control.

Employing User Controls

A user control provides the easiest way to combine several controls onto a single control that can simply be dragged onto a Web page without writing much code. Many times, pages contain similar controls. For example, when prompting a user for a billing address and a shipping address, the controls to retrieve the name, address, city, state, and zip code are duplicated. This is where user controls can be very handy. You can create a user control containing the name, address, city, state, and zip code and drop it onto a Web page where needed. User controls are built using similar procedures to those that are required to build a standard Web page. Web pages can even be converted to user controls with little effort. User controls inherit from the UserControl class, which inherits from the Template-Control class, which inherits from the Control class, as shown in Figure 5-1.
 

Creating a User Control

User controls have a standard naming convention, which uses an .ascx extension to ensure that the control is not executed in a stand-alone fashion. You can create a user control in Visual Studio 2005 by choosing Website, Add New Item, Web User Control. On the surface, it appears that a new Web page was added. However, a quick glance at the HTML reveals a Control directive instead of a Page directive, as follows:
'VB

<%@ Control Language="VB"
 AutoEventWireup="false"
 CodeFile="MyControl.ascx.vb"
Inherits="MyControl"
 %>

//C#

<%@ Control Language="C#"

AutoEventWireup="true"

CodeFile="MyControl.ascx.cs"

Inherits="MyControl"
%>

All text and controls that are added to this user control are rendered on the page that the control is added to. For example, a Label called lblName and a TextBox called txt-Name are placed on the user control, as shown below, and the user control can be added to any Web page where required.
'VB
<%@ Control Language="VB"
 AutoEventWireup="false"
CodeFile="MyControl.ascx.vb" Inherits="MyControl" %>

<asp:Label ID="lblName" runat="server" Text="Label">
</asp:Label>
<asp:TextBox ID="txtName" runat="server" ></asp:TextBox>
//C#
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="MyControl.ascx.cs" Inherits="MyControl" %>

<asp:Label ID="lblName" runat="server" Text="Label">
</asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

Creating a User Control from a Web Page

In addition to explicitly creating a user control, you can also convert a Web page to a user control. The primary benefit is that you can do your prototyping and testing without having to deal with placing the control on a Web page.

The procedure for converting a Web page to a user control is as follows:

1. Remove the <html>, <body>, and <form> begin and end tags.
2. Change the @Page directive at the top of the file to an @Control directive.
3. Change the file extension of your Web page from .aspx to.ascx.
4. In the @Control directive, change Inherits="System.Web.UI.Page" to Inherits="System.Web.UI.UserControl".

Adding a User Control to a Page

You can add a user control to a Web page by simply dragging it from the Solution Explorer and dropping it on a Web page. When you add the user control to the page, a look at the HTML reveals the following additions to the page:

<%@ Page Language="language" AutoEventWireup="false" CodeFile="Default.aspx.language" Inherits="_Default" %>
<%@ Register Src="MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:MyControl ID="MyControl1" runat="server" />
</div>
</form>
</body>
</html>

Notice the @Register directive at the top of the page. This is a requirement to place the controls on the page. The TagPrefix attribute is a namespace identifier for the control. The default TagPrefix is uc1 (as in User Control 1) and is changeable. The TagName attribute is the name of the control to use. The Src attribute is the location of the user control. The instance of MyControl is in the form tag. Notice that the ID is automatically created as MyControl1, the next instance will be called MyControl2, and so on.

Accessing Data from the User Control

If this user control is placed on a Web page, the TextBox and Label are visible to the user, but how can the name be retrieved? The TextBox and Label controls are declared as protected members on the Web page, which means that they are accessible only to the MyControl class and to classes that inherit from the control. To access the data for the Label and TextBox, you could expose the properties that are required, such as the Text property of the txtName TextBox and the Text property of the lblName Label. The user control is a class and can contain properties and methods. You can add properties to the user controls called UserName and UserCaption, as follows:

'VB
Partial Class MyControl
Inherits System.Web.UI.UserControl
Public Property UserCaption() As String
  Get
Return lblName.Text
       End Get
 
                  Set(ByVal value As String)
        lblName.Text = value
                  End Set
                End Property

Public Property  UserName() As String
  Get
Return txtName.Text
End Get
Set(ByVal value As String)
txtName.Text = value
End Set
 End Property
End Class
 
//C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MyControl : System.Web.UI.UserControl
    {
       public string UserCaption
         {
get
{
return lblName.Text;
 }
  set
  {
   lblName.Text = value;
}
  }
public string UserName
      {
get { return txtName.Text; }
   set { txtName.Text = value; }
  }
          }

To demonstrate the new properties, the MyControl user control, a Button control, and a Label control are added to the Web page, and code is added to the code-behind page of the Web page to retrieve the UserName, as follows:

ASPX File

'VB
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="MyControlPropertyTest.aspx.vb Inherits="MyControlPropertyTest" %>
<%@ Register Src="MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>
<!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>
<br />
<asp:Button ID="Button1" runat="server" Text="Get Name"
OnClick="Button1_Click" />
<br />
<br />
<uc1:MyControl ID="MyControl1" runat="server" />
<br />
<br />
<asp:Label ID="Label1" runat="server" ></asp:Label>
</div>
</form>
</body>
 </html>

 //C#
<%@ Page Language="C#" AutoEventWireup="true"CodeFile="MyControlPropertyTest.aspx.cs" Inherits="MyControlPropertyTest" %>
<%@ Register Src="MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>
<!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>
<br />
<asp:Button ID="Button1" runat="server" Text="Get Name"
OnClick="Button1_Click" />&nbsp;<br />
<br />
<uc1:MyControl ID="MyControl1" runat="server" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<br />
</div>
 </form>
</body>
</html>

Code-Behind
'VB
Partial Class MyControlPropertyTest Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load

MyControl1.UserCaption = "Enter User Name:"

End Sub
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click

Label1.Text = MyControl1.UserName

End Sub
End Class
//C#

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MyControlPropertyTest : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
   {
       MyControl1.UserCaption = "Enter User Name:";
   }
protected void Button1_Click(object sender, EventArgs e)
   {
       Label1.Text = MyControl1.UserName;
   }

}

Positioning User Controls

 When a user control is dropped onto a Web page, you always position it using some of the same techniques as you would use to position other controls using Flow Layout, such as placing the user control in an HTML table. You’ll soon find that you cannot position the user control using Dynamic Hypertext Markup Language (DHTML) to set the absolute positioning using the Style property because the user control does not automatically add an outer tag for the contents of the control that could be assigned a Style. You can set the positioning using DHTML if you add a Panel control to the Web page and place the user control into the Panel. This allows the Panel and its contents to be positioned.

Conclusion

1) The User Control enables a Web developer to easily combine controls onto a single control that can be dragged from the Solution Explorer window and dropped onto a Web page. 
2) Because the user control contains an .ascx markup file, a user control cannot be compiled to a .dll and shared; it can only be shared within a Web site. 
3) You can expose properties, events, and methods in a user control.

About the author
Zaheer is a .NET developer and he is having more than 3 years of experience in ASP .Net, C#. He is working on ASP .Net 2.0 and Sql Server 2005 since beta 2 versions.