One of the most powerful features of ASP.NET is being able to define your own redistributable controls using the existing ASP.NET control framework in .Net 2.0. In this post we will identify 2 types of control:
- User Controls
- Custom Controls
We will focus mainly on custom controls, but we will take a quick look at user controls also. We will talk about when to use which and why.
User controls and custom controls in ASP.NET allow you to create feature rich controls of your own, and you may take this path for several reasons - the most popular are that you have a recurring piece of UI/logic in your site and you want to consolidate that to one central source, and the other is that you want to commercially create and distribute controls.
User Controls V Custom Controls
As a rule of thumb use custom controls when you intend to deploy and distribute your controls to several applications (perhaps you are creating a suite of controls for sale?), and use user controls when they are required for the one off application, or an in house application.
User Controls
User controls are created by adding a .ascx file to your website, once you have done that you can add existing controls (standard ASP.NET 2.0, or 3rd party) just like you would do a regular .aspx page, you can also use the normal page events for this control. They are quick and easy to create, they are compiled when requested.
Here is an example of a dead easy control that displays the name of a person selected from a drop down list.
MyUserControl.ascx
1 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
2
3 <asp:DropDownList
4 ID="ddlPeople"
5 runat="server"
6 AutoPostBack="true"
7 OnSelectedIndexChanged="ddlPeople_SelectedIndexChanged" />
8
9 <p>
10 <strong>Selected Person: </strong>
11 <asp:Label
12 ID="lblPerson"
13 runat="server" />
14 </p>
MyUserControl.ascx.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Web;
4
5 public partial class MyUserControl : System.Web.UI.UserControl {
6
7 protected void Page_Load(object sender, EventArgs e) {
8 if (!Page.IsPostBack) {
9 List<string> people = new List<string>();
10 people.Add("Granville Barnett");
11 people.Add("James Bond");
12 people.Add("Betty Boo");
13
14 ddlPeople.DataSource = people;
15 ddlPeople.DataBind();
16 }
17 }
18
19 protected void ddlPeople_SelectedIndexChanged(object sender, EventArgs e) {
20 lblPerson.Text = ddlPeople.SelectedItem.Text;
21 }
22
23 }
The example contains no clever logic - it simply demonstrates how easy it is to create a user control! All the events used are exactly the same had we created this functionality using a normal web form - the difference being that we have identified a recurring piece of UI/logic for my site so I have decided to create a reusable control. I don't want to spend any more time on user controls - they have their use but I am far more interested in custom controls which are distributed as normal class libraries (.dll).
Custom Controls
As I have mentioned before these are distributed as pre-compiled libraries, they offer a wealth of depth and power and for this first post we will simply create a label like control - we will then use it in a sample site, and look at how to configure the web.config appropriatley so we can use it.
Derive from System.Web.UI.Control or System.Web.UI.WebControls.WebControl? A general rule is that if you need to render HTML or some visual output then derive from the WebControl class, if you don't require any visual rendering then derive from the Control class.
Ok, so lets get going and create a simple custon control. This control will behave like a label with with less features!
1 using System;
2 using System.Web.UI;
3 using System.Web.UI.WebControls;
4
5 namespace Org.GBarnett.Controls {
6
7 public class SimpleControl : WebControl {
8
9 private string _text;
10
11 public string Text {
12 get { return _text; }
13 set { _text = value; }
14 }
15
16 protected override void Render(HtmlTextWriter writer) {
17 writer.Write("{0}", _text);
18 }
19
20 }
21
22 }
To render the control we override the virtual Render method of the WebControl class, also because we derive from WebControl our control automatically has options for Css-Class, ViewState etc. Of note is that we have one property name Text this is where the user can..you guessed it enter text! Thats all there is to this! This is the first in a series of posts on custom controls so hopefully you will be comfortable with creating a custom control after reading this...hopefully!
No we have coded up a custom control build the solution then create a web site project and add a reference to the .dll of the control. With that done add a web.config file to your web site solution and add the following xml:
40 <pages>
41 <controls>
42 <add
43 assembly="Name of your assembly"
44 namespace="Namespace of control"
45 tagPrefix="Tag prefix for your control" />
46 </controls>
47 </pages>
Now we have wired our control up in the web.config we can use the control freely within our project, e.g.
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <html xmlns="http://www.w3.org/1999/xhtml" >
6 <head runat="server">
7 <title>Untitled Page</title>
8 </head>
9 <body>
10 <form id="form1" runat="server">
11 <div>
12
13 <gb:SimpleControl
14 ID="gbTest"
15 Text="Granville Barnett"
16 runat="server" />
17
18 </div>
19 </form>
20 </body>
21 </html>
That covers everything I wanted to go over today, in the future I will cover more advanced topics, as well as wiring your control up with relevant attributes so that users can get design time support for your control.
Until then :-)
Share this post: Email it! | bookmark it! | digg it! | reddit!