Export (0) Print
Expand All

Creating Web User Controls

You design Web user controls in much the same way that you design Web Forms pages. You can use the same HTML elements and Web controls on a user control that you do on a standard Web Forms page. However, the user control does not have <HTML>, <BODY>, and <FORM> elements in it, and the file name extension must be .ascx.

To create a Web Forms user control

  1. Create a Web project. For details, see Creating Web Projects.
  2. On the Project menu, click Add Web User Control. Change the name as desired and click Open to open the control in the designer.
  3. Add text and controls to the design surface. Any controls that you want to be able to access programmatically must be Web Forms server controls or HTML server controls.
  4. Use the Web Forms Designer to set properties and create any code required for your control.

The following example shows a simple user control that you might use as a menu. The four menu choices are implemented as Hyperlink Web server controls.

<!-- Visual Basic --> 
<%@ Control Language="vb" AutoEventWireup="false"
    Codebehind="menu.ascx.vb" Inherits="myProj.menu"
    TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<P>
<asp:HyperLink id="lnkLogin" runat="server"
    NavigateURL="Login.aspx">Login</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkAddToCart" runat="server" 
   NavigateURL="Cart.aspx">Add to Cart</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkTechSupport" runat="server" 
   NavigateURL="TechSupport.aspx">Technical Support</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkAbout" runat="server" 
   NavigateURL="AboutUs.aspx">About Us</asp:HyperLink>
</P>

<!-- C# --> 
<%@ Control Language="c#" AutoEventWireup="false" 
    Codebehind="menu.ascx.cs" Inherits="myProj.menu" 
    TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<P>
<asp:HyperLink id="lnkLogin" runat="server" 
   NavigateURL="Login.aspx">Login</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkAddToCart" runat="server" 
   NavigateURL="Cart.aspx">Add to Cart</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkTechSupport" runat="server"
   NavigateURL="TechSupport.aspx">Technical Support</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkAbout" runat="server" 
   NavigateURL="AboutUs.aspx">About Us</asp:HyperLink></P>

See Also

Introduction to Web User Controls | Adding User Controls to a Web Forms Page | Introduction to Web Custom Controls | Recommendations for Web User Controls vs. Web Custom Controls | Walkthrough: Creating a Web User Control

Show:
© 2014 Microsoft