Monday, 9 April 2012

What is an ASP.NET User Control?

An ASP.NET user control is a group of one or more server controls or static HTML elements that encapsulate a piece of functionality. A user control could simply be an extension of the functionality of an existing server control. Its extension is .ascx.

A user control typically resides on a page with other elements. This breakup of functionality could be the basis of an entire application built with independent and reusable user controls. The controls could then be dynamically loaded into different areas of the page.

User Control vs. Other Controls:

One source of confusion when working with ASP.NET knows the difference between the many different types of controls.

For Example:  An ASP.NET control is a server-side component that is shipped with .NET Framework. A server control is a compiled DLL file and cannot be edited. It can, however, be manipulated through its public properties at design time or runtime.

User control will consist of previously built server controls. It has an interface that can be completely edited and changed. It can be manipulated at design-time and runtime via properties that you are responsible for creating.


1. Reuse of same code.
2. Helps in fragment caching.

 Difference between Web page and User controls:

1. Web pages have directive <%@ Page %> while user controls have directive <%@ Control %>
2. Web pages have extension .aspx while user controls have extension .ascx.
3. User controls cannot be directly used.

Page and User Control classes have been derived from the same class. So, both have almost same properties.

Hierarchy: Object --> Control --> TemplateControl --> Page and UserControl

To include a user control in your aspx page, just write Register directive like:

<%Register TagPrefix="cr" TagName="Footer" src="Footer.ascx"%>

Web user controls can be loaded dynamically using LoadControl method provided by Page class.

Types: Independent and Integrated

Independent: These are user controls which contain static HTML which can be included on the page and they have nothing to do with the logic of the page.

Integrated: It deals with the functionality of the page in which it is included.

How to create integrated user controls?

Suppose there is a user control which has one textbox which asks for username and another textbox asks for password and a button named submit. Now we will create two EVENTS, one sucessfulLogin and another unsucessfulLogin and button click event. When button is clicked and username/password is correct, we will raise sucessfulLogin event and else unsucessfulLogin event.

Now the hosting page will create event handler for these events and can do whatever it wants to do with those events.

No comments:

Post a Comment