Page 160 - DCAP312_WEB_TECHNOLOGIES_II
P. 160
Web Technologies-II
Notes 8.2.4 How to Create Instances of ASP.NET User Controls Programmatically
To create an instance of a user control programmatically
In the user control, be sure that the @ Control directive contains a ClassName attribute that
assigns a class to the user control. The following example sets the ClassName attribute to
strongly type a user control.
<%@ Control class Name= “MyUserControl” %>
In the page where you want to work with the user control, create a reference to the user control
with the @ Reference directive.
When you create the user control programmatically, the strong type for your user control is
available to the ASP.NET Web page only after you have created a reference to it. For example,
the following code creates a reference to a user control created in the MyUserControl.ascx file.
Create an instance variable for the user control, using the control’s class name. The class will
be part of the ASP namespace.
If you want to create an instance of the user control declared as class Spinner,
you use syntax such as the following:
VB
Protected Spinner1 As ASP.Spinner
C#
Protected ASP.Spinner Spinner1
• Create an instance of the user control in code by calling the LoadControl
method.
• Assign property values as necessary, and then add the control to the
ControlCollection collection of a container on the page, such as a PlaceHolder
control.
8.2.5 How to Create Templated ASP.NET User Controls
You can create user controls that implement templates, an ASP.NET feature that allows the
separation of control data from its presentation. A templated control does not provide a user
interface. Instead, it is written to implement a naming container and to include a class whose
properties and methods are accessible to the host page.
The user interface for the user control is supplied by a page developer at design time. The
developer creates templates of the type defined by the user control, and can then adds controls
and markup to the templates.
To create a template user control
1. In the .ascx file, add an ASP.NET PlaceHolder control where you want the template to
appear.
2. In the user control’s code, implement a property of type ITemplate.
3. Define a server control class that implements the INamingContainer interface as a container
in which to create an instance of the template. This is called the template’s naming container.
4. Apply the TemplateContainerAttribute to the property that implements ITemplate and pass
the type of the template’s naming container as the argument to the attribute’s constructor.
5. In the control’s Init method, repeat the following steps one or more times:
• Create an instance of the naming container class.
• Create an instance of the template in the naming container.
• Add the naming container instance to the Controls property of the PlaceHolder server
control.
154 LOVELY PROFESSIONAL UNIVERSITY