Creating a UserControl
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.
Having problems with this chapter? Ask in our forums!
Could this article help your friends? Please help us to help them by sharing it on Facebook or Twitter: