Follow in Twitter & Facebook

Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools

Saturday, August 11, 2012

Asp.Net User Control

In this article we will discuss about what is an user control and how to create an use user control in Also you can check my last article on Access Master Page controls from the Content Page in Asp.Net here and you can see some SharePoint 2013 articles and SharePoint 2010 articles.

- A user control is a reusable control in we can make a single user control and can reuse that in different pages.

- User control extension is .ascx

- We can write HTML code as well as we can write code file in .cs file.

- The code file is inherited from System.Web.UI.UserControl.

- User controls can not be directly requested, they must be embedded with a .aspx page.

It is very easy to create an user control in Visual Studio 2010.

To add one use control Right click on the project -> Add new item and from the Add New Item dialog box select Web user control and give name and click on Add as shown in the figure below:

This will create the user control.
By default the html code will appear.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TestUserControl.ascx.cs" Inherits="TestUserControl" %>

Then we will put one label where we will print something.

So the HTML code will be:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TestUserControl.ascx.cs" Inherits="TestUserControl" %>

<asp:Label ID="lblWelcome" runat="server" Text=""></asp:Label>

And .CS code:

protected void Page_Load(object sender, EventArgs e)
        lblWelcome.Text = "Hello World of User Control !!!";
This step finishes our creation user control part. In the next step we will see how to call this user control in .aspx page.

1st Approach:

For this we have to add through Register attribute and we need to give tagname, tagprefix and source name like below:

<%@ Register src="TestUserControl.ascx" tagname="TestUserControl" tagprefix="uc1" %>

Then we need to call like below:
<uc1:TestUserControl ID="TestUserControl1" runat="server" />

where uc1 in the tagprefix and TestUserControl is the tag name.

2nd Approach:

This is the simplest approach, Just drag and drop the user control to the page where you want to the design view.

0 on: "Asp.Net User Control"