Programmatically Instantiating a User Control


Programmatically Instantiating a User Control

Because the type for a user control is dynamically generated, a user control cannot be created programmatically using the new syntax for instantiating a class. To create a user control programmatically, you must invoke the LoadControl method of the containing page. The LoadControl method takes the relative path to a user control source file and returns an object of type Control , which you can cast to the strong type of the user control. The page shown in Listing 4-15 programmatically creates the user control LinkGlyph and casts it to its strong type. The Reference directive specifies the relative path to the .ascx file for the user control. The page uses the PlaceHolder control to mark a location in the page for rendering the dynamically added user control.

Listing 4-15 LoadControlTest.aspx
 <%@PageLanguage="C#"%> <%@ReferenceControl="UserControls/LinkGlyph.ascx"%> <html> <head> <scriptrunat="server"> protectedoverridevoidOnLoad(EventArgse){ LinkGlyphdemo=(LinkGlyph) Page.LoadControl("UserControls/LinkGlyph.ascx"); demo.NavigateUrl="CruiseSelectorTest.aspx"; demo.Text="ClickMe"; holder.Controls.Add(demo); } </script> </head> <body> <formid="form"runat="server"> <p> <asp:PlaceHolderid="holder"runat="server"/> </p> </form> </body> </html> 

When a page creates a user control programmatically, it does not need to register a tag prefix or tag name for the user control if it does not have any declarative instances of that user control. In that case, a page should have the Reference directive instead of the Register directive, as shown in Listing 4-15.



Developing Microsoft ASP. NET Server Controls and Components
Developing Microsoft ASP.NET Server Controls and Components (Pro-Developer)
ISBN: 0735615829
EAN: 2147483647
Year: 2005
Pages: 183

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net