Category Archives: User Control
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"> <controls> <add tagPrefix="cc1" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit"/> <add tagPrefix="my" tagName="FormFields" src="~/CustomControls/MyFormFields.ascx"/> </controls> </pages>
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.
Web User Control Events
Ever want to have an event for a Web User Control that the parent page can consume? Well you can, and it is fairly simple.
I am not an expert since I just figured this out myself so here we go.
There are three basic things you need to do for each event.
- Create a public delegate variable in your User Control
- Create a public event event for the type of delegate
- Create a protected virtual method
So lets see some code.
//Public variables and methods public delegate void ItemClickEvent(object sender, EventArgs e); public event ItemClickEvent ItemClick; //Protected Methods protected virtual void OnItemClicked(object sender, EventArgs e) { if (ItemClick != null) { ItemClick(this, e); } }
The property in the page with this user control will be called OnItemClick. Notice I do not have anything named OnItemClick. The only public names are ItemClickEvent, which is a delegate and the event itself, ItemClick. So I assume that .NET adds the On to the front of your event name.