TOC

The community is working on translating this tutorial into Italian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

UserControls:

Creating a UserControl

Okay, so we will be building a UserControl for displaying information about a community user. First of all, let's add a UserControl to our project. In your Visual Studio, you should be able to right click on your project and select Add new item.. A dialog will pop up, and you should select the Web User Control from the list of possible things to add. Let's call our UserControl UserInfoBoxControl, with the filename of UserInfoBoxControl.ascx. Make sure that you have checked the checkbox which places code in a separate file, the so-called CodeBehind file.

You should now have a UserInfoBoxControl.ascx and a UserInfoBoxControl.ascx.cs in your project. The first is where we put our markup, and the second is our CodeBehind file. Now, if UserInfoBoxControl.ascx is not already open and selected, do so now. You will see only one line of code, the UserControl declaration. As mentioned, this control will be displaying information about a user, so let's get started adding some markup to do so:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserInfoBoxControl.ascx.cs" Inherits="UserInfoBoxControl" %>
<b>Information about <%= this.UserName %></b>
<br /><br />
<%= this.UserName %> is <%= this.UserAge %> years old and lives in <%= this.UserCountry %>

As you can see, it's all very basic. We have a declaration, some standard tags, some text, and then we have some sort of variables. Now, where do they come from? Well, right now, they come from nowhere, since we haven't declared them yet. We better do that right away. Open the CodeBehind file for the UserControl, that is, the one which ends on .cs.

As you can see, it looks just like a CodeBehind file for a regular page, except that it inherits from UserControl instead of from Page. We will declare the tree properties used in our markup, and base them on three corresponding fields.

private string userName;
private int userAge;
private string userCountry;

public string UserName
{
    get { return userName; }
    set { userName = value; }
}

public int UserAge
{
    get { return userAge; }
    set { userAge = value; }
}

public string UserCountry
{
    get { return userCountry; }
    set { userCountry = value; }
}

It's all very simple and works just like a regular class. You can even add methods, if you feel like it! Our UserControl is actually done now, but as you may have already experienced, we can't use it yet. A UserControl can't be displayed directly in the browser - it has to be included on a page. We will do that in the next chapter.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!