Creating a asp.net UserControl and use in asp.net page

Creating a asp.net UserControl and use in asp.net page:

In this post we try to create user control in asp.net. and how to use this control in asp page with C# code.

Welcome to this ASP.NET Tutorial Place, currently consisting of posts, these are covering all the most important ASP.NET concepts. This tutorial is primarily for new users of this great technology, and we recommend you to go through all the post, to get the most out of it as possible. While each post can be used without reading the previous posts, some of them may reference things done in earlier post.


asp.net UserControl and use in asp.net page:

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.

asp.net 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.


Other Related Post : Asp.net and Sql Database:

Comments