6 February 2014

User Controls in Asp.net

         User controls behaves like miniature ASP.Net pages, or web forms, which could be used by many other pages. These are derived from the System.Web.UI.UserControl class. These controls have the following characteristics.
·         They have an Extension .ascx
·         They may not contain <html><body> or <form>  tags
·         They contain control directive instead of page directive
Steps to Create User Control:
·         Create a new web application.
·         Right click on the project folder on the Solution Explorer and choose Add New Item.
·      Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially footer.ascx contains only a Control directive
<%@ Control Language="C#" AutoEventWireup="true"
               CodeBehind="footer.ascx.cs"
               Inherits="customcontroldemo.footer" %>
·         Add the following code to the file:
<table>
<tr>
<td align="center"> Copyright ©2010 TutorialPoints Ltd.</td>
</tr>
<tr>
<td align="center"> Location: Hyderabad, A.P </td>
</tr>
</table>

·         To add the user control to your web page, you must add the Register directive and an instance of the user control to the page. The following code shows the content file:
<%@ Page Language="C#" AutoEventWireup="true"
         CodeBehind="Default.aspx.cs"
         Inherits="customcontroldemo._Default" %>
<%@ Register Src="~/footer.ascx"
             TagName="footer" TagPrefix="Tfooter" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server"
         Text="Welcome to ASP.Net Tutorials "></asp:Label>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server"
        onclick="Button1_Click"  Text="Copyright Info" />
       
       </div>
       <Tfooter:footer ID="footer1" runat="server" />
    </form>
</body>
</html>
·         When executed, the page shows the footer and this control could be used in all the pages of your site.
Registering User Control
·         The Register directive specifies a tag name as well as tag prefix for the control.
<%@ Register Src="~/footer.ascx" TagName="footer"
                                    TagPrefix="Tfooter" %>
·         This tag name and prefix should be used while adding the user control on the page:
<Tfooter:footer ID="footer1" runat="server" />


No comments:

Post a Comment