User control functionally allows packing and reusing any UI desired. Although ASP.NET server controls is largely functional but they cannot cover every situation. Web user controls define controls easily as desired for the application, using the same programming techniques as used to write Web Forms pages. Web Form pages can be converted into a Web user control with a few modifications. To make sure that a user control cannot be run as a stand alone Web Forms page, user controls are identified by the file name extension. ascx.
A Web user control is similar to a complete Web Forms page, with both a user interface page and a code-behind file. The user interface page differs from an .aspx file in these ways:
In every other way, a user control is like a Web Forms page. Similar HTML elements and Web controls can be used on a user control as done on a standard Web Forms page. For example, if you are creating a user control to be used as a toolbar, you can put a series of Button Web server controls onto the control and create event handlers for the buttons.
The following example is a simple user control, which encapsulates the user login form.
<table bgcolor="orange" style=font: 10pt verdana;border-width:1;border-style:solid;border-color:black;" cellspacing=15>
<td><ASP:TextBox id="User" runat="server"/></td>
<td><b>Password: </b></td> <td><ASP:TextBox id="Pass" TextMode="Password" runat="server"/></td>
<td><ASP:Button Text="Submit" runat="server"/>
Name the user control and save it with an .ascx file name extension. For example, you can name it as Logonform.ascx . Note that it looks very similar to the HTML portion of an ASP.NET page.
It contains two text box controls, i.e. a button control, and a label control and a table to provide formatting. However it doesn’t include any <html>, <form> or <body> tags. You can not see its output directly because first it needs to be placed in an ASP.NET page.
How to call Logonform.ascx file into .aspx file?
When the user control is included in a Web Forms page, it is important to include this file name, and the path to the file, in the @ Register directive's Src attribute as shown below: -
<%@ Register tagprefix=" tagprefix" Tagname=" tagname" Src="pathname" %>
An alias to associate with a namespace.
An alias to associate with a class.
The namespace to associate with tagprefix.
The location (relative or absolute) of the declared user control file to associate with the tagprefix: tagname pair.
It is implemented in following example.
|Example 13 call_ascx.aspx
<%@ Register tagprefix="EXPERT" Tagname="Logonform" Src="Logonform.ascx" %>
<EXPERT:Logonform id="Logon" runat="server"/>
<asp:Label id="lblMessage" runat="server"/>