</div>
</form> Dynamically Load User Control
Use LoadControl method in Page class which takes path to control definition, n.b. Control must be registered with page.
After control has been loaded it must be added to page.
AddressUc addressControl = (AddressUc)LoadControl("AddressUSerControl.ascx");
form1.Controls.Add(addressControl);
Templated User Controls
Provides separation of control data from its presentation.
Does not provide default UI layout - instead provided by developer who uses control on a page.
- Add user control file web application
- Add PlaceHolder control to controls markup - defines place holder for templated layout. PlaceHolder exposed as control property and used by developers to define their markup layout code.
<%@ Control... %><asp:PlaceHolder runat="server" ID="PlaceHolderAddressTemplate" />
- Create class file to server as naming container for control. A naming container allows a contained child to be found using FindControl. In addition to containing controls also need to reference data on which control works. Naming container class inherits from Control and implements INamingContainer interface. Should contain public properties for data elements it contains.
- In code behind file implement property of type ITemplate. This serves as template for users of the control (and exposes PlaceHolder created in step 2). Apply the TemplateContainerAttribute to this property, passing type of naming class container (step 3) as argument to constructor. Apply PersistenceModeAttribute attribute to ITemplate property, passing PersistenceMode.InnerProperty to the attributes constructor.
- In Page_Init method of user control test for ITemplate property. If set, create instance of naming container and instance of template in naming container. Add naming container instance to controls collection of PlaceHolder control.
- May need to pass data from control to naming container - allows users to set control properties and store them using container. Define data in user control as properties that developer can set, pass reference to this data to naming container.
Using Templated Control
Drag templated control from Solution Explorer to page which will register control with page.
Then define template for user control layout by nesting within <LayoutTemplate>
tags.
Inside template reference data via Container object.
<uc1LAddressUcTemplate ID="AddressUcTemplated1" runat="server">
<LayoutTemplate>
<asp:TextBox ID="addr1" runat="server" Text="<%#Container.Address.AddressLine1%>" />
</LayoutTemplate>
</uc1LAddressUcTemplate>
In the code behind file call the Page.DataBind to bind container to templated layout:
protected void Page_Load(object sender, EventArgs e)
{
AddressUcTemplated1.Address.AddressLine1 = "1234 Some St.";
Page.DataBind();
}
Downloads