How to register User Control to a Web Form
Sep 11, 2012 00:00 · 265 words · 2 minute read
what is the user control ?
Its similar to ASP.NET Web page but
- The extension is .ascx
- can not run as stand-alone files and need to add to a web form
- do not have html, body or form elements
How to Register User Control in a Web Form?
firstly you need to add the user control into your project as a new item .
Then in order to use it ,there are two options to add a user control into a web form.
The first option is :
- Make it accessible to a specific web form if you need the user control only accessible to a specific web form, the user control can register to it by adding below line to the top of your web form :
<%@ Register Src="userControlOne.ascx" TagName="TheTag" TagPrefix="uc1" %>
Src is pointing to user control file name
TagPrefix and TagName is the unique combination to call the user control in a web form content
and then to call the registered user control in web form use below code :
<uc1:TheTag ID="uniqueIdForPartOne" runat="server"></uc1:TheTag>
the second option is :
- Make it accessible to all forms
In this case , you need to register it to the Web.config file with below code to the
element :
pages>
<controls>
<add tagPrefix="uc1" tagName="TheTagTwo" src="~/controls/userControlTwo.ascx"/>
</controls>
</pages>
In order to resolve the address of user control from the root file , you should use ‘~’ symbol. then you can use the user control from any web form without registering it again, in the same way :
<uc1:TheTagTwo ID="uniqueIdForPartTwo" runat="server"></uc1:TheTagTwo>
download the userControl source from my GitHub.