Next


User Controls

• Similar to “User Controls” in windows applications, you can develop user controls in the web sites also.
• As you know already, the advantage of user controls is, those can be used in any web page, and avoids designing repetitive content in multiple pages.

Implementation of User Controls

1. Add the User Control to the Web Site:
• Click on “Web Site” menu – “Add New Item”.
• Select “Web User Control”.
• Enter the name of the user control and click on “Add”.
• Note: The file extension for web control file is “.ascx”. (Active Server Control Extended).
• Then the user control will be created with the following statement in the “Source” view.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
2. Design and Develop the User Control
• Design the user control, as per on your requirement. Drag the required controls from the toolbox, (just like web page) and write the code in the “.ascx.cs” file if needed.
3. Link the User Control with the Web Page
• To do this, type the following tag in the “Source” view, after “<%@ Page>” tag.
<%@ Register Src="UserControlFileName" TagPrefix="xxxx" TagName="xxxx" %>
4. Invoke the User Control
• To invoke the control in the page, use the following tag, whereever required. <Tagprefix:TagName />

Demo on User Controls

Usercontrils


Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/MyUserControl.ascx" TagPrefix="uc1" TagName="Header" %>

<!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>
       <uc1:Header runat="server" />
        <br /><h1 align="center">Welcome to Home Page</h1>
    </div>
   </form>
</body>
</html>