Archive

Posts Tagged ‘user control’

ASP.NET: Create user Control

May 24, 2011 Leave a comment

In this article, we will be building a simple User Control to demonstrate how a ASP.NET User Control can be added into a ASPX page.

 

Assuming that you created an Empty Web Application from Visual Studio, you now create a new User Control by right-click on your web application > Add > New Item and name it MyUserControl.ascx. Then click Add.

aspnet_userControl_create

Now, you have created your User Control. Now, lets put in some text so that we can see it in the web page later.

aspnet_userControl_ascx

Next, we will add this User Control into our ASPX web page. First, you have to register your User Control on the top of your page, under the @Page declaration. You should add the @Register declaration like below.

 

<%@ Register src="UserControl/MyUserControl.ascx" tagname="MyUserControl" tagprefix="uc1" %>

 

The “src” property should be pointing to where your ASCX file is located. Then you can name the “tagname” and “tagprefix” property. By default, the “tagname” will be your User Control file name, and the “tagprefix” will be “uc1” if you are adding the first User Control in the page.

 

Next, you add the control into your page like how you add a Button  or Label into your webpage. Add the following code into the Body.

 

<uc1:MyUserControl ID="MyUserControl1" runat="server" />

 

Your ASPX page code should look like the following.

aspnet_userControl_aspx

Now, save and run your code. You will see that your User Control is loaded into the web page. You have just successfully added a custom User Control into your web page.

Categories: ASP.NET Tags: , ,