ASP.NET Architecture, Part 2 - Adding Controls
(Page 5 of 7 )
Adding a User Control Declaratively
Two methods exist for adding the control to a web form page. The first method allows you to place the control declaratively. Create a new web form page called GreetContainer.aspx, and place it in the virtual directory where you saved Register.ascx. Write the following code:
<%@ Page Language = "vb" %>
<%@ Register TagPrefix = "ASPNETsbtn" TagName=RegisterClient"
Src = "Register.ascx" %>
<html>
<head>
<script runat="server">
Sub Page_Load(Sender as Object, E As EventArgs)
MyRegister.Name = "Steve"
MyRegister.GreetClient
End Sub
</script>
</head>
<body>
<ASPNETsbtn:RegisterClient id= "MyRegister" runat ="server"/>
</body>
</html>
The output is as expected:
Please register to
use our services, Steve
Adding a User Control Programmatically
Adding a user control to a web forms page programmatically is similar to the declarative method, but with a few changes. Create a new web forms page named RegisterMoreClients.aspx. Then, save it to the same directory as you did previously:
<%@ Page Language = "vb" %>
<%@ Reference Control = "Register.ascx" %>
<html>
<head>
<script runat="server">
Sub Page_Load(Sender As Object, E as EventArgs)
Dim MyRegister As Control = LoadControl("Register.ascx")
RegisterHolder.Controls.Add(MyRegister)
CType(MyRegister.Register).Name = "Steve"
CType(MyRegister.Register).GreetClient
End Sub
</script>
</head>
<body>
<asp:placeholder id="Referenceholder" runat="server"/>
</body>
</html>
The @ Reference directive tells ASP.NET to compile and link the user control Register.ascx with the page when compiled. The Placeholder control allows you to insert a placeholder in the HTML markup so you can add a control to a specific location on the page. Reference the saved page just as you did previously from the Internet Services Manager. Right-click this page, and select Browse to render the page to the browser.
This has been part two of ASP.NET Architecture (see part 1 here), chapter six of .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004).
Buy this book now. |
Next: Server Control Types and Web Controls >>
More ASP.NET Articles
More By McGraw-Hill/Osborne