Click here to Skip to main content
Click here to Skip to main content

Programatically include an ASP.NET UserControl in a Web Page

, 9 Mar 2002
Rate this:
Please Sign up or sign in to vote.
A tutorial on how to programatically include an ASP.NET UserControl in a web page.
<!-- Download Links --> <!-- Article image -->

Sample Image - ASPNetUserControl2.gif

<!-- Add the rest of your HTML here -->

In one of the earlier articles by Chris Maunder, User controls in ASP .NET, and a similar article by us, ASP.NET User Controls - 1, the highlights of ASP.NET usercontrols have been discussed. These previous artciles demonstrated how to create a UserControl and do declarative inclusion in the web page. This article will discuss programatic inclusion of the UserControls. As you will see that this process is not a rocket science, thanks to ASP.NET framework. A lot of details are already there in Microsoft documentation. 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 programatically 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 programatic inclusion but still some users skipped those steps.

Make sure that you specify the className attribute in @Control directive in the .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" <span style="color:red;">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 a control in web 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 was 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 want to 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 the 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 programatic inclusion of UserControl is pretty straight forward.

In the coming days we will be posting more articles demostrating various aspects of UserControl development. So If you have any suggestions or would like to some feature to be demonstrated, please feel free to write us at softomatix@pardesiservices.com or visit us at Softomatix

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Softomatix
Web Developer
United States United States
To learn more about us, Please visit us at http://www.netomatix.com

Comments and Discussions

 
GeneralLocations inUserControls Pinmemberdankyy126-Dec-04 22:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 10 Mar 2002
Article Copyright 2002 by Softomatix
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid