Using Web User Controls

So you’ve written a nice little Web User Control, but how do you use it?

Using your Web User Control is actually really simple. I am not going to address creating one just how to add that reference to your nice little .ascx file. There are two ways to do this, as a page directive or as I prefer, in the web.config file.

<%@ Register Src="MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>

For myself I prefer to use the web.config setting. In your controls section which is inside the pages section you just add them. In my example below I wanted to show one that goes to a dll (the Ajax Control Toolkit) and one that goes to an ascx file inside a UserControl folder in my project.

<pages viewStateEncryptionMode="Always">
    <add tagPrefix="cc1" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit"/>
    <add tagPrefix="my" tagName="FormFields" src="~/CustomControls/MyFormFields.ascx"/>

You will reference your control with <tagPrefix:tagName>.  The tagPrefix is the first half of the control tag and should be fairly obvious and is something you control.  So instead of <asp:  you would have <my: or <cc1:  For the other half of the tag it is a bit different, the ascx sets the tag name, <my:FormFields  …. />  In the namespace one it will be one of the objects in the dll, <cc1:Accordian … />.

Please see the MSDN site for Walkthrough: Creating Reusable Elements with ASP.NET User Controls.

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on April 25, 2012, in .NET, User Control and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: