TOC

This article is currently in the process of being translated into French (~28% done).

UserControls:

Creating a UserControl

Bon, nous allons donc créer un UserControl pour afficher des informations sur un utilisateur de la communauté. Tout d’abord, ajoutons un UserControl à notre projet. Dans votre Visual Studio, vous devriez pouvoir cliquer avec le bouton droit de la souris sur votre projet et sélectionner Ajouter un nouvel élément. Une boîte de dialogue s'ouvre. Vous allez sélectionner le " Contrôle Utilisateur Web " dans la liste des éléments à ajouter. Appelons notre UserControl UserInfoBoxControl, avec le nom de fichier UserInfoBoxControl.ascx. Assurez-vous que vous avez coché la case à cocher qui place le code dans un fichier séparé, appelé fichier CodeBehind.

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!