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.
| Example:12 Logonform.ascx |
<table bgcolor="orange" style=font: 10pt verdana;border-width:1;border-style:solid;border-color:black;" cellspacing=15>
<tr>
<td><b>Login: </b></td>
<td><ASP:TextBox id="User" runat="server"/></td>
</tr>
<tr>
<td><b>Password: </b></td> <td><ASP:TextBox id="Pass" TextMode="Password" runat="server"/></td>
</tr>
<tr>
<td>
</td>
<td><ASP:Button Text="Submit" runat="server"/>
</td>
</tr> <
/table> |
| |
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" %>
Where…
tagprefix
An alias to associate with a namespace.
tagname
An alias to associate with a class.
Namespace
The namespace to associate with tagprefix.
Src
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" %>
<html>
<body>
<form runat="server">
<EXPERT:Logonform id="Logon" runat="server"/>
</form>
<p>
<asp:Label id="lblMessage" runat="server"/>
</body>
</html>
|
| |