| Details | ![]() |
| QuickDocId | 400 |
| Written by | Imar Spaanjaars |
| Posted | 07/23/2006 16:11 |
| Page views | 7507 |
| Listened to | Saturday Morning by Eels (Track 2 from the album: Shootenanny!) |
Are you looking to hire an experienced software developer or .NET consultant? Then get in touch with me through my company's web site at devierkoeden.com
Found an interesting article on this site? Got inspired by something you read here? Then consider making a donation with PayPal.
User Controls are very common in today's ASP.NET websites, both in version 1.x as in version 2.0. Many sites use them to reuse content, like a menu, a header or a footer or even for partial page content, like a shop's product catalog.
However, User Controls can be used for more than simply displaying static, repeating content. With a bit of knowledge about how User Controls work, you can teach them a few tricks. By adding public properties to a User Control, they become much more powerful and easier to reuse.
In this article I'll show you how to build a User Control that displays information about an article, like a news item, similar to the Details section that you find at the top of most pages in my site.
Although I am using Visual Studio 2005 and ASP.NET 2.0 in this article, the same principles and code work for Visual Studio .NET 2002 / 2003 and ASP.NET 1.x as well.
Before I show you how to build such a control, let's briefly consider the current functionality of the control. On each page on my website, you see one or more "Infopanels" in the left-hand bar. For the page you're viewing right now, the first Infopanel looks similar to this (note that the Modified date and Page views may be slightly different):

Figure 1 - The Article Details User Control
This info panel shows a number of properties of the article, like my name, the article's QuickDocId and the number of times it has been viewed. Instead of hard coding the Infopanel in a page, it has been wrapped inside a User Control called ArticleDetails. This User Control exposes public properties that allows you to set the values for the article properties like the author's name. These properties are then used to build up the control. You'll see how this works later.
When you design such functionality for your own site, you may be tempted to create this panel in the main page directly. After all, the content for the panel is closely related to the main page you're working with. However, abstracting the functionality away to a separate User Control is a good idea for the following reasons:
In the next section, I'll walk you through creating the control and giving it some external properties that are used to fill the labels for QuickDocId, Written by and so on.

Figure 2 - The Article Details User Control in Design View in VWD
The next step is adding public properties to the control, so the contents of these labels can be filled with the values of these properties. Since every public property needs a private backing variable, you should start off with creating those and then let the refactoring functionality of Visual Studio create the properties for you. (Note, Refactoring is only available for C# and only then in a limited form in Visual Web Developer. For VB.NET, you can use the free Refactor! from Developer Express. Don't worry if you don't have a refactoring menu in Visual Studio; you can always type the code manually.)
C#
public partial class ArticleDetails : System.Web.UI.UserControl
{
private string quickDocId = String.Empty; private string writtenBy = String.Empty; private DateTime posted = DateTime.MinValue; private int pageViews = 0; private string listenedTo = String.Empty;
protected void Page_Load(object sender, EventArgs e) { } }
VB.NET
Partial Class ArticleDetails Inherits System.Web.UI.UserControl
Private _quickDocId As String = String.Empty Private _writtenBy As String = String.Empty Private _posted As DateTime = DateTime.MinValue Private _pageViews As Integer = 0 Private _listenedTo As String = String.Empty
End Class
private string quickDocId = String.Empty;
public string QuickDocId
{
get { return quickDocId; }
set { quickDocId = value; }
}
Private _quickDocId As String
Public Property QuickDocId() As String
Get
Return _quickDocId
End Get
Set(ByVal value As String)
_quickDocId = value
End Set
End Property
The final step you need to perform in the control is to assign the value of these properties to the labels in the markup at run-time. An ideal location for this is inside the Load event of the page. Add the following to the code behind of the page:
C#
protected void Page_Load(object sender, EventArgs e)
{
lblQuickDocId.Text = quickDocId;
lblWrittenBy.Text = writtenBy;
lblPosted.Text = posted.ToString();
lblPageViews.Text = pageViews.ToString();
lblListenedTo.Text = listenedTo;
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
lblQuickDocId.Text = _quickDocId
lblWrittenBy.Text = _writtenBy
lblPosted.Text = _posted.ToString()
lblPageViews.Text = _pageViews.ToString()
lblListenedTo.Text = _listenedTo
End Sub
This code fills in the various labels defined in the markup when the control is loaded at run-time.
The last step in the process is to create an ASPX page that hosts the control and sets its properties.
Figure 3 - The User Control ArticleDetails on the host page
With the User Control on the page, you have three different ways to influence the properties of the ArticleDetails control: directly in the HTML markup, through the control's Property Grid or programmatically in the code behind of the page. Figure 4 shows how the Code Editor is able to display Intelli Sense for the custom properties:
Figure 4 - Intelli Sense Popping Up for the ListenedTo Property of the User Control
Figure 5 shows the Property Grid for the control, with a few properties set:
Figure 5 - The Property Grid for the ArticleDetails Control
You can see that the properties are listed under the Data category in the Property Grid. You can assign properties to existing categories (like Behavior and Data) or to new ones you invent yourself by adding a Category attribute to the property, like this:
C#
[ Category("Data") ] public string ListenedTo { get { return listenedTo; } set { listenedTo = value; } } VB.NET
<Category("Data")> _ Public Property ListenedTo() As String Get Return _listenedTo End Get Set(ByVal value As String) _listenedTo = value End Set End Property
Instead of hard-coding the values in the markup of the page, you'll often find yourself setting these kind of properties programmatically at run-time. For instance, you could have a News business object that exposes the relevant properties. The following code snippet shows how you can set the properties at run-time:
C#
protected void Page_Load(object sender, EventArgs e)
{
ArticleDetails1.QuickDocId = "167";
ArticleDetails1.WrittenBy = "Imar Spaanjaars";
ArticleDetails1.Posted = new DateTime(2006, 7, 23);
ArticleDetails1.PageViews = 231;
ArticleDetails1.ListenedTo =
"Open Your Arms by Editors (Track 10 from the album: The Back Room)";
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
ArticleDetails1.QuickDocId = "167"
ArticleDetails1.WrittenBy = "Imar Spaanjaars"
ArticleDetails1.Posted = new DateTime(2006, 7, 23)
ArticleDetails1.PageViews = 231
ArticleDetails1.ListenedTo = "Open Your Arms " & _
"by Editors (Track 10 from the album: The Back Room)"
End Sub

As you have seen, building User Controls that can be influenced at run-time is pretty easy. All you need to do is add a number of publicly accessible properties to the User Control in its Code Behind file. These properties then automatically become available in the page hosting the User Control so you can set them declaratively or programmatically.
Wonder where to go next?
You can read existing comments below
or you can post a comment yourself on this article.
Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.
I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.
When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.
If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.
For more information about the Talk Back feature, check out this news item.
| QuickDocId | 400 |
| Full URL | http://imar.spaanjaars.com/400/building-smarter-user-controls |
| Short cut | http://imar.spaanjaars.com/400/ |
| Written by | Imar Spaanjaars |
| Date Posted | 07/23/2006 16:11 |
| Listened to when writing | Saturday Morning by Eels (Track 2 from the album: Shootenanny!) |