Creating Web User Controls in ASP.NET With Examples

MinalS's Avatar author of Creating Web User Controls in ASP.NET With Examples
Examples with detailed explanation of how a custom user control for web is created in ASP.NET.
Developers use various web server controls to enable users to interact with the web pages. Sometimes there is a functionality for which there is no built in control. For example, if the user has created a customized page with some labels, textboxes, and one button to enable the user to log on the website. If the user wants to use the same login page in all other applications, a custom control is created.

The custom controls can be created by combining two or more controls and can be reused in different web applications. The different types of custom controls can be as follows:
  1. Web User control
  2. Web custom control
  3. Templated User control

Web User control



The web user controls are containers that can be created by combining one or more web server controls. After creating a Web user control, you can treat it as a unit and define properties and methods for it. They are similar to the ASP.NET web pages in the context that they contain both a user interface page and code.

A web user control is created in the same way as the user creates the ASP.NET page. Bit it differs from an ASP.NET web page in the following ways.
  • The file name extension of the user control is .ascx
  • A user control contains the @Control directive instead of the @Page directive
  • They cannot run as stand alone files. They need to be added to the ASP.NET pages to make them work.
  • User controls do not have <html>, <body>, or <form> elements. The elements must be present on the web page that is hosting these conttols.
A web user control on a web page must be registered before it is used. The @Register directive as shown below:
Code:
%@Register TagPrefix=”ABC” TagName=”Header” Src=”mycontrol.ascx” %
The markup contains the following three attributes as mentioned below:
  • TagPrefix: It specifies the alias to associate the namespace of the user control
  • TagName: It specifies the alias associated with the class of the user control
  • Src: It specifies the virtual path of the file containing the user control
After registering the control, user can include it by writing markup as shown below:
Code:
<ABC: Header ID=”mycontrol” runat=”server”>
To create and use a user control in ASP.NET, follow the steps mentioned below:

1. Create a new application in Visual Studio
2. Right click on the project folder in the Solution Explorer and select the ‘Add New Item’ option.



3. Select the Web User control from the Add New Item dialog box and name it. It contains the control directive as shown below:
Code:
<%@ Control Language=”C#” AutoEventWireUp=”true” CodeFile=”WebUserControl.ascx.cs” Inherits=”WebUserControl” %>
4. Add the following code to the user control file.
HTML Code:
<table>
<tr>
<td align=”left”>Demo of the user control </td>
</tr>
<tr>
<td align=”left”>The control can be added on any web page </td>
</tr>
</table>
5. To add the user control to the web page, add the Register directive and an instance of the user control to the page. The following code snippet is shown:
Code:
<%@ Register Src=”~/WebUserControl.ascx” TagName=”User” TagPrefix=”TUser” %>
<form id=”form1” runat=”server”>
<div>
<asp:Label ID=”lbl1” runat=”server” Text=”Welcome User”></asp:Label>
<br/>
<asp:Button ID=”btn1” runat=”server” Text=”Show”></asp:Button>
</div>
<TUser: User ID=”user1” runat=”server” />
</form>
6. The output for the code is as shown below:



Web custom control



There are situations when we need a control containing properties that are not provided by the existing server control. In such conditions user cannot use the web server control because the user control is created by combining one or more server controls.

Web custom controls provide an approach to reuse the logic in an ASP.NET application. They are written as classes. They are written by using the managed code and does not contain any markup files.

Web custom controls are of the following types:

1. Controls that combine two or more existing controls:

This type of control is known as a composite control and can be created by deriving the class from System.Web.UI.Control or System.Web.UI.WebControl. It overrides the CreateChildControls method of the base class.


The steps for creating a composite control in ASP.NET are as follows:

1. Open Visual Studio, click ‘File’ > ‘Project’ > ‘Add ASP.NET Server Control application’
2. Name the file to an appropriate name



3. Navigate to the .cs page of the control and add the following code
Code:
public class ServerControl1: WebControl
{
    protected TextBox txt=new TextBox();
    protected Label lbl=new Label();
    protected Button btn=new Button();
    public string Text
    {
         get
          {
                EnsureChildControls();
                return txt.Text;
          }
          set
          {
                  EnsureChildControls();
                  Txt.Text=value;
           }
        }
        protected override void CreateChildControls()
        {
              Base.CreateChildControls();
              lbl.Text=”UserID: <br>”;
              btn.Text=”Submit”;
              this.Controls.Add(lbl);
              this.Controls.Add(btn);
              this.Controls.Add(txt);
          }
}
4. Next, open the AssemblyInfo.cs and write the following code.
  • Add the namespace using System.Web.UI;
  • At the end of the file, write the assembly name as follows:[assembly:TagPrefix(ServerControl1”,”sc”)]
5. Build the application by clicking the build solution option and close the application
6. Add a new project, go to the Solution Explorer
7. Right click on it and add the existing project
8. Add the control project to the website project
9. Right click on the solution explorer and set as start up project
10. Right click on the website project and add the reference of the project name
11. Go to add reference and select the add project name as ServerControl2
12. Add the dll file from the add reference window and click OK
13. The control will appear in the toolbox of the application



14. Drag and drop the control from the toolbox and the source file will appear as follows
Code:
<%@ Register assembly=”ServerControl2” TagPrefix=”CC” Namespace=”ServerControl2” %>
<CC: ServerControl1 ID=”ServerControl1” runat=”server”>
15. The output for the code is as shown below:



2. Controls that extend the functionality of an existing control:

This type of control is created when an existing control meets the most of the requirements but lacks some features. In such conditions, user can customize the existing control by defining a class that derives from the class corresponding to the existing control.

The steps for creating the control are as follows:

1. Open the website in the visual studio application
2. Add a new Class Library project to the solution
3. Add the reference to the System.Web assembly
4. Rename the class as NewButton.cs to the project.
5. Type the following code in the class
Code:
using System.Web.UI.WebControls;

public class NewButton:Button()
{
        Width=100;
        Height=150;
}
protected override void OnClick ( EventArgs e)
{
        int count=Convert.ToInt32 ( this.Text) + 1;
        this.Text=count.ToString();
}
6. Select the File - > Save All option and save the file
7. Right click on the library and select Build. The control is ready to use. The dll for the control is created and stored in the Bin\Debug folder
8. To use the control, create a new web solution and add a web page to it
9. Open the Design view of the web page
10. Add a new tab by the name Extended Controls to the Toolbox window
11. Drag the NewButton control from the ToolBox window and drop in the Default.aspx web page



12. Save the files and press the F5 Key to execute application
13. The output for the code is as shown below:



3. Controls that are not similar to any existing control:

This type of control created when none of the existing control meets the user requirements. The user can create a custom control by deriving from the System.Web.UI.Control or System.Web.UI.WebControl class.

The steps for creating the control are as follows:

1. Open the website for which the user wants to create the custom control
2. Right click on the solution explorer and select the ‘Add New Item’ option.
3. Select the class template from the Visual Studio templates section
4. Type the name as CurrentDate.cs and click Add button
5. Type the following code in the class
Code:
public class CurrentDate1 : WebControl
{
    string Color;
    public string color
    {
          get
          {
                     return Color;
          }
          set
          {
                   Color=value;
          }
          
    }
   protected override void RenderControls( HtmlTextWriter w)
   {
         w.Write(“<FONT color=”+Color+”>”+DateTime.Now+”<FONT>”);
   }
}
6. Right click on the aspx file and select the View code option
7. Type the following code in the code behind file
Code:
protected void Page_Load ( object sender, EventArgs e)
{
        CurrentDate1 c=new CurrentDate1();
        c.Color=”#ff0000”;
        this.Controls.Add (c);
}
8. Execute the code and the output is as shown below:



Templated Control



A templated user control allows the user to modify the layout of the interface by defining the templates. The controls allow the separation of the controls from the presentation. They do not have a user interface but implement the container and include the class whose properties and methods are accessible to the page.

The steps for creating a templated control is as shown below

1. Open the website in which you want to add the templated control
2. Right click on the Solution Explorer, select Add New Item option
3. Select the Web User Control template from the section
4. Type MyTemplatedControl.ascx as the name in the textbox and click Add button
5. Right click the ascx file and select the view markup. The source view window will be opened
6. Type the following code in the window
Code:
<asp:PlaceHolder ID=”PlaceHolder1” runat=”server” />
7. In the code behind file of the user control, type the following code
Code:
public partial class WebUserControl1: System.Web.UI.Control
{
	[TemplatedContainer(typeof(ItemContainer))]
         
	public ITemplate ItemTemplate
	{
	get
	{
		return ItemTemplate;
	}
	set
	{
		ItemTemplate=value;
	}
}
[TemplateContainer ( typeof( ItemContainer))]
public ITemplate AlterantingItemTemplate
{
	get
	{
		return AlternatingItemTemplate;
	}
	set
	{
		AlternatingItemTemplate=value;
	}
}
private bool isodd ( int i)
{
	if(i%2 == 0)
		return false;
	else
		return true;
}
void Page_Init()
{
	String[ ] students = {“Sam”, “Harry”, “Nancy” };
	for (int i=0; i<4; i++)
	{
		ItemContainer con=new ItemContainer ( stuents [i]);
		if( isodd (i))
		{ 
			AlternatingItemTemplate.InstantiateIn (con);
		}
		else
		{
			ItemTemplate.InstantiateIn ( con);
		}
		PlaceHolder1.Controls.Add( con);
	}
}
public class ItemContainer : Control, INamingContainer
{
	private String s_name;
	internal ItemContainer (String name)
	{
		s_name=name;
	}
	public String Name
	{
		get
		{
			return s_name;
		}
	}
}
8. Save all the contents of the file
9. Right click in the solution explorer and select the default.aspx page. Open the View markup of the page
10. Add the following code in the aspx page
Code:
<%@ Register Src=”~/MyTemplatedControl.ascx” TagName=”MyTemplateControl” TagPrefix=”uc1” %>
<div>
    <uc1: MyTemplateControl ID=”MyTemplate” runat=”server” />
    <ItemTemplate>
      <font color=”blue”>
        <asp:Label ID=”lbl1” runat=”server” Text=’<%# Container.Name %>’ />
        </font>
         <hr/>
      </ItemTemplate>
      <AlternatingItemTemplate>
         <font color=”green”>
          <asp:Label ID=”lbl2” runat=”server” Text=’<%# Container.Name %>’ />
          </font>
          <hr/>
       </AlternatingItemTemplate>
  </div>
11. In the code behind file of the default page, type the following code in the Page_Load event.
Code:
DataBind();
12. Press F5 and run the code. The output for the code is as shown below:

shabbir like this