@ Reference

Declaratively indicates that another user control or page source file should be dynamically compiled and linked against the page in which this directive is declared.

<%@ Reference page | control="pathtofile" %>

Attributes

  • Page
    The Web Forms page that ASP.NET should dynamically compile and link the current page against at run time.
  • Control
    User control that ASP.NET should dynamically compile and link the current page against at run time.

Remarks

Using this directive allows you to dynamically compile a user control and add it to the ControlCollection object, accessed through the Controls property, for the page or server control. This allows you to cast the returned type after you have called the LoadControl method (inherited by the page from the TemplateControl class).

Example

The following example demonstrates using this directive to link a user control, MyControl.ascx, and load it to a containing page using the LoadControl method. When it is loaded to the page, the user control's MyProperty value is set, and the user control is added to a PlaceHolder server control's ControlCollection object through the Controls property.

<%@ Reference Control="MyControl.ascx" %>
<script language="C#" runat=server>

    void Page_Load(Object sender, EventArgs e) {

       // In the @ Control directive in the MyControl.ascx file, 
       // you must include classname="MyControl" for this to work.
        MyControl myControl = (MyControl) Page.LoadControl("MyControl.ascx");
        myControl.MyProperty = "Color";

        PlaceHolder.Controls.Add(myControl);
    }

</script>

<html>
      <body>
                 <asp:placeholder id="PlaceHolder" runat=server/>
   </body>
</html>
[VisualĀ Basic]
<%@ Reference Control="MyControl.ascx" %>
<script language="VB" runat=server>
   Sub Page_Load(sender As Object, e As EventArgs)

       ' In the @ Control directive in the MyControl.ascx file, 
       ' you must include classname="MyControl" for this to work.  
      Dim myControl As MyControl = CType(Page.LoadControl("MyControl.ascx"), MyControl)
      myControl.MyProperty = "Color"
      
      PlaceHolder.Controls.Add(myControl)
   End Sub
</script>

<html>
<body>
    <asp:placeholder id="PlaceHolder" runat=server/>
</body>
</html>

See Also

Directive | ASP.NET Web Forms Syntax | Web Forms User Controls | Introduction to Web Forms Pages