Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Creating Instances of UserControls Declaratively and Programmatically

4.09/5 (6 votes)
2 Feb 2010CPOL6 min read 37.8K   307  
This articles explains creating Instance of User Controls Declaratively and Programmatically

Introduction

When you need extra functionality in a control that is not provided by the built-in ASP.NET Server controls, then you have two options:

  • User controls: 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.
  • Custom controls: A custom control is a class that you write that derives from Control or Web Control.

User controls are easier to create than custom controls, because you can reuse existing controls. Web User control or the .ascx file in ASP.NET is a replacement for the include file feature in ASP. Web user controls are derived from System.Web.UI.UserControl namespace. They can be added to the aspx page either at design time or programmatically during run time. But they lack the design time support of setting the properties created along with the control. They cannot run on their own and they need to stand on another platform like an aspx page. Even if we try to load it on a web browser, IIS will not serve the files of the type .ascx.

Using the Code

  1. Creating User Controls Declaratively: Declarative syntax for user controls is similar to that of ASP.NET Web page. The main difference is that the controls don't include HTML, body and form elements as in a web page around the content. Also the controls use @Control directive while ASP.NET web page uses @Page Directive.

    Here I will create a simple user control to display item summary, with an image and label control:

    • Create new web application.
    • Right click on the project in the Project Explorer and click Add - Add New Item and select a Web User Control item. This adds a file with the extension .ascx to the project. This is the file that the user control will use to expose its interface. An .ASCX file cannot be viewed directly in the browser. It will need to be placed within a container (such as another Web form) to be viewed. The following line is added in the .ascx file:
      ASP.NET
      <%@ Control Language="C#" AutoEventWireup="true"
          CodeFile="ItemSummary.ascx.cs" Inherits="Controls_ItemSummary"
          ClassName="Controls_ItemSummary" %> 

      Add the following code to .ascx file after the above line:

      C#
        1   1  <table cellpadding="0" cellspacing="0" runat="server"
        2     width="100%" id="tblUC">
        3   2     <tr>
        4   3          <td width="15%">
        5   4              <asp:Image ID="imgItem" runat="server"
        6                 AlternateText="No   ImageAvaliable"/>
        7   5             </td>
        8   6             <td>
        9   7               <asp:Label ID="lblSummary" runat="server"/>
       10   8             </td>
       11   9       </tr>
       12  10  </table>
      

      Now open the .ascx.cs file and add the properties for the control.

      C#
        1   1  protected override void OnPreRender(EventArgs e)
        2   2      {
        3   3          imgItem.ImageUrl = itemImageURL; // sets the Image
        4   4          lblSummary.Text = itemSummary; //sets text for the summary
        5   5      }
        6   6
        7   7      // to get item summary
        8   8
        9   9      private string itemSummary;
       10  10      public string ItemSummary
       11  11      {
       12  12          get{ return itemSummary; }
       13  13          set{ itemSummary = value; }
       14  14      }
       15  15
       16  16      // to get set item image URL
       17  17
       18  18      private string itemImageURL;
       19  19      public string ItemImageURL
       20  20      {
       21  21          get{return itemImageURL;}
       22  22          set{itemImageURL = value; }
       23  23      }
      
    • Open your solution explorer and drag the user Control to a web page in designer view. This will add the following code in the aspx file, which actually registers the control on the aspx page.
      ASP.NET
      <%@ Register Src="Controls/ItemSummary.ascx" TagName="ItemSummary"
          TagPrefix="uc1" %> 

      Once the control is registered on the page, you can freely add many instances of the controls to the page.

      • TagPrefix: specifies the prefix to use for the control(s). It is sort of like a namespace in which several controls might share a single prefix value. This is why all ASP.NET server controls specify the asp prefix. The only difference is that the ASP.NET server control directive is implied and not explicitly declared.

      • TagName: specifies the name of the control.

      • Src: Location of the control.

      • runat='server': to manipulate the user control programmatically. Otherwise, only the raw HTML is sent back to the browser.

    • The following code is added within the form tags of the User control container:
      ASP.NET
      <uc1:ItemSummary ID="ItemSummary1" runat="server"
          ItemSummary="My Summary goes here"
          ItemImageURL="~/App_Themes/Images/monitor.gif" />
  2. Creating User Controls Programmatically: We can create the instances of User Controls Programmatically just like ASP.Net Server controls on a web forms page. The instances can be created by calling the LoadControl() method of the containing page.
    • Strong Type User Control: User control is Strongly Typed by adding the ClassName attribute in the @Control directive, which assigns class name to the User Control. This is required because the LoadControl( ) method has a return type of Control class. For that, you have to cast the control to its class name as to access its properties and methods.
      ASP.NET
      <%@ Control Language="C#" ClassName="Controls_ItemSummary"
      	AutoEventWireup="true" CodeFile="ItemSummary.ascx.cs"
      	Inherits="Controls_ItemSummary" %> 
    • Register Control on the Working page: Now the second step is to register the control on the page where you will create its instance, by using the @Reference directive. When you create the user control programmatically, the strong type for your user control is available to the ASP.NET Web page only after you have created a reference to it. For example, the following creates a reference to a user control file.
      ASP.NET
      <%@ Reference Control="~/Controls/ItemSummary.ascx" %> 

      However when instances of user controls are created declaratively @ Register directive is used.

    • Creating Instance Variable of the User Control: Now create an instance of the user control using controls class name. The controls class will be a part of ASP namespace. For example, if the controls class name is ItemSummaryControl.
      C#
      protected ASP.Controls_ItemSummary ucItemSummary;
    • Creating instance by calling LoadControl( ) Method: Now create the instance of the control by calling LoadControl( ) method. The LoadControl( ) method reads the file and instantiates it as a control that can be added to the page. For example:
      C#
        1   1    for (int i = 1; i < 5; i++)
        2   2  {
        3   3      //Load Control
        4   4      ucItemSummary=(ASP.Controls_ItemSummary)LoadControl
        5                 ("~/Controls/ItemSummary.ascx");
        6   5
        7   6      //Set Control properties
        8   7      ucItemSummary.ItemSummary = "My Control " + i.ToString();
        9   8      ucItemSummary.ItemImageURL = "~/App_Themes/Images/monitor.gif";
       10   9
       11  10       //Break between the controls
       12  11       phControlHolder.Controls.Add(new LiteralControl("<br/>"));
       13  12
       14  13       //Add Control to the Place Holder
       15  14       phControlHolder.Controls.Add(ucItemSummary);
       16  15   }
      
    • When you add controls to the ControlCollection object using the Add method, they are placed in the collection in the order they are processed. If you want to add a control to a specific position in the collection, use the AddAt method and specify the index location where you want to store the control.

Advantages of a Web User Control

The biggest advantage of the Web User controls is that they can be created as a site template and used throughout the site. For example, they can be made to contain the Menu/Link structure of a site and can be used at all the other aspx pages. This means the following:

  1. If the website introduces a new site-wide link within the current layout/structure, it is enough if we put it on the user control once. All pages will be updated once if the web user control is used in them.
  2. If there is any link to be corrected, it can be done once at the server side.
  3. The .ascx files can either be used as a simple alternative to the plain HTML or they can also be used to respond to events. This means even custom code can be created against them and put in the code behind files.

Drawbacks / Disadvantages

Though the User controls offer a flexibility of having site wide modifications, if the whole structure of the site changes, the HTML/aspx code of all the pages should be modified. But as long as the site maintains a same layout, then Web User controls are the number one choice for maintaining the generic layout of the site.

Another disadvantage is that it cannot just be simply referenced for using in a different project. If we want to use this User Control in a different project, we have to copy the file and modify the namespace to the host namespace name.

History

  • 2nd February, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)