Click here to Skip to main content
13,589,923 members
Click here to Skip to main content
Add your own
alternative version


65 bookmarked
Posted 9 Mar 2002

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"


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;
				leftLogoImg = new System.Web.UI.WebControls.Image();
				leftLogoImg.ImageUrl = this.m_strLeftLogoImgPath;
			catch (Exception ex)

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;
			hdrCtl = LoadControl("./controls/SiteHeader.ascx");
			if (hdrCtl != null)
				((SiteHeader)hdrCtl).LeftLogoImgPath = "..\\images\\ps_logo.gif";
				((SiteHeader)hdrCtl).RightLogoImgPath = "..\\images\\ps_name.gif";
		catch (Exception ex)

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 or visit us at Softomatix


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


About the Author

Web Developer
United States United States
To learn more about us, Please visit us at

You may also be interested in...

Comments and Discussions

QuestionDynamically adding hyperlinks to a panel which is added into the webpart Pin
Member 329072229-Jan-09 19:50
memberMember 329072229-Jan-09 19:50 
QuestionView state ??? Pin
khalidahmad27-Oct-08 2:36
memberkhalidahmad27-Oct-08 2:36 
AnswerRe: View state ??? Pin
Mike Holpuch27-Oct-08 3:02
memberMike Holpuch27-Oct-08 3:02 
QuestionHow to use user control in a class Pin
cagacu2-Jul-07 21:45
membercagacu2-Jul-07 21:45 
QuestionMy application name what? Pin
ElvinK18-Nov-06 19:09
memberElvinK18-Nov-06 19:09 
GeneralLocations inUserControls Pin
dankyy126-Dec-04 21:10
memberdankyy126-Dec-04 21:10 
GeneralEvent Handling in Programatic User Controls Pin
Chuck Lane3-Aug-04 11:11
memberChuck Lane3-Aug-04 11:11 
GeneralThe Challenge Pin
_jaso20-Aug-03 21:57
member_jaso20-Aug-03 21:57 
GeneralRe: The Challenge Pin
puco17-Sep-03 0:05
memberpuco17-Sep-03 0:05 
GeneralRe: The Challenge Pin
puco17-Sep-03 0:25
memberpuco17-Sep-03 0:25 
GeneralRe: The Challenge Pin
_jaso17-Sep-03 13:31
member_jaso17-Sep-03 13:31 
GeneralRe: The Challenge Pin
Malby10-Nov-03 13:19
memberMalby10-Nov-03 13:19 
GeneralRe: The Challenge Pin
Malby10-Nov-03 13:20
memberMalby10-Nov-03 13:20 
GeneralRe: The Challenge Pin
_jaso10-Nov-03 14:35
member_jaso10-Nov-03 14:35 
GeneralRe: The Challenge - Solution? Pin
Anonymous24-May-05 3:28
sussAnonymous24-May-05 3:28 
GeneralYou assume we all use Visual Studio Pin
_jaso20-Aug-03 20:47
member_jaso20-Aug-03 20:47 
GeneralRe: You assume we all use Visual Studio Pin
Stefan Prodan3-May-07 7:30
memberStefan Prodan3-May-07 7:30 Pin
jagadeeshkel15-Aug-03 20:39
memberjagadeeshkel15-Aug-03 20:39 
GeneralForm Statement Error... Pin
MikeRoad12-Aug-03 13:13
memberMikeRoad12-Aug-03 13:13 
GeneralRe: Form Statement Error... Pin
snowsurfer300018-Aug-03 12:49
membersnowsurfer300018-Aug-03 12:49 
GeneralRe: Form Statement Error... Pin
Anonymous19-Aug-03 19:54
sussAnonymous19-Aug-03 19:54 
QuestionDoes So Many Control References affects performance? Pin
HEROSP24-Jul-03 12:38
memberHEROSP24-Jul-03 12:38 
AnswerRe: Does So Many Control References affects performance? Pin
Softomatix24-Jul-03 13:15
memberSoftomatix24-Jul-03 13:15 
QuestionUserControl? Pin
Agyklon11-Nov-02 13:41
memberAgyklon11-Nov-02 13:41 
GeneralFine example, except... : ( Pin
Anonymous20-Sep-02 10:18
sussAnonymous20-Sep-02 10:18 

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

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

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