Home
Products
Forums
Help
Publish Article
Go Freelance

How to Programtically Include ASP.Net User Controls

Downloads

If you are seeing this section and do not see download links, this means that you are not logged into our site. If you already are a member, click on the login link and login into site and come back to this page for downloading the control files. If you are not a member, click on registration link to become a Winista member and download the control for free.

In the previous articles ASP.Net User Controls - 1 we discussed some highlights of writing ASP.Net user controls and we demonstrated how to write couple of simple UserControls. In that article we mentioned that UserControls can be programtically loaded in the web page. This article will discuss programtic inclusion of the UserControls. As you will see that this process is not a rocket science, thanks to ASP.Net framework. But there are some things that you need to be aware of and shall take into consideration.

Todos In Control Declaration

We have seen that a lot of users who have tried to programtically include UserControl on the web page, ran into some compile time and run time errors. And we are no exception to that kind of category of users. Although MS documentation has mentioned steps that need to be followed for programtica inclusion but still some of use skipped those steps.

  • Make sure that you specify the className attribute in @Control directive in .ascx file implementing your UserControl. What this means is that when you include the control in a web page and create an instance of it then you can refer to the control by its strong type name as specified in className attribute. If you don't specify this attribute, then framework appends _ascx to the class name of that control, defined in codebehind source file, and assigns it to the control. For example in our case we developed a UserControl named "SiteHeader". The declaration in the code behind file looks like
    public abstract class SiteHeader : System.Web.UI.UserControl
    												
    In this case, if you don't specify className attribute in @Control directive then page will load this control with strong name SiteHeader_ascx.
    This is one of the problems that people have run into. For example, when we tried to type case the user control to SiteHeader type, it failed. The reason was simple that it was created as type SiteHeader_ascx and not SiteHeader. So @Control in the control's ascx file should look something like this.
    <%@ Control Language="c#" AutoEventWireup="false"
     Codebehind="SiteHeader.ascx.cs" classname="SiteHeader"
     classname="SiteHeader" Inherits="ASPNet_App.Controls.SiteHeader">
    												
  • And then you need to follow the procedures for creation and implementation of actual control functionality. In our case we have defined two string properties for the SiteHeader contorl. These properties are used to specify the path for the images that need to be displayed in the control. at load time, in Page_Load event of the control, we check if the path for these images have been specified or not. If there is no path, then we skip the inclusion of asp:Image control. Here is the fragment of the code that we have used.
    private void Page_Load(object sender, System.EventArgs e)
    {
    	if (!IsPostBack)
    	{
    		// If the file path has been specified for left logo
    		// image then add a image control to the cell.
    		if (this.m_strLeftLogoImgPath.Length > 0)
    		{
    			//TODO: Check if the file path is valid or not.
    			System.Web.UI.WebControls.Image  leftLogoImg;
    			try
    			{
    				leftLogoImg = new System.Web.UI.WebControls.Image();
    				leftLogoImg.ImageUrl = this.m_strLeftLogoImgPath;
    				this.LeftLogoCell.Controls.Add(leftLogoImg);
    			}
    			catch (Exception ex)
    			{
    				Trace.Write(ex.Message);
    			}
    		}
    	}
    }												
    												

Todos In WebPage Loading UserControl

When you want to programtically include a UserControl in a web page, the steps are different than those followed for delarative inclusion of control in weg page.

  • For declarative inclusion of control in the page, you used @Register directive at the top of the page. But for programatic there is going to be a change. You will use @Reference directive. This directive takaes only one attribute, Page or Control. The value of this attribute specifies the file that contains the control or the page that this page should link to during dynamic compliation. This step is very important, otherwise your will get Compiler Error CS0246 indicating that class name or type not found.
    <%@ Reference Control="./controls/SiteHeader.ascx"%>
    												
  • If you have created your UserControl in a namespace different than the the web application, then you need to add using directive for that namespace if you don't wantt o use the fully qualified name for the control's type.
    using ASPNet_App.Controls;
    												 
  • And then the last step of actually loading the UserControl in the web page. In the Page_Load event for the page, call LoadControl method. This method is defined in System.Web.UI.TemplateControl class. And System.Web.UI.Page class inherits from Template class.
  • If LoadControl method succeeds, it loads the UserControl from the specified file and returns a reference to that control.
  • You can access the properties and methods of the loaded control from the reference returned on the previous step.
private void Page_Load(object sender, System.EventArgs e)
{
	if (!IsPostBack)
	{
		// Load the Header UserControl.
		Control hdrCtl = null;
		try
		{
			hdrCtl = LoadControl("./controls/SiteHeader.ascx");
			if (hdrCtl != null)
			{
				((SiteHeader)hdrCtl).LeftLogoImgPath = "..\\images\\ps_logo.gif";
				((SiteHeader)hdrCtl).RightLogoImgPath = "..\\images\\ps_name.gif";
				HeaderCtl.Controls.Add(hdrCtl);
			}
		}
		catch (Exception ex)
		{
			Trace.Write(ex.Message);
		}
	}
}										
										

If all the steps are followed correctly and the proper declarations have been included, then programtic inclusion of UserControl is pretty straight forward.

Go Freelance
Home     About us     Contact us    Copyright    Privacy Policy    Return Policy    Advertisers
Copyright © Netomatix