How to: Create Templates Dynamically in DataList Web Server Controls
Templates do not have to be assigned at design time. In some situations, you might be able to lay out the template at design time, but changes you know you will make during run time are so extensive that loading a new template at run time simplifies the programming. In other cases, you may have several possible templates but want to change the template at run time.
To create a template definition file
Create a new text file with an .ascx extension.
Add template definition statements to the template file and save it, using the same markup that you would use in any declarative template.
The following example shows the content of an .ascx file with the markup for a template that contains data-boundcontrols. The data binding will be resolved at run time against the data source that is bound to the DataList control.
Name: <asp:Label ID="CategoryNameLabel" runat="server" Text='<%# Eval("CategoryName") %>'> </asp:Label> <br /> Description: <asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>'> </asp:Label>
To create templates dynamically
Add code to your Web Forms page to load the template using themethod. This method reads a template definition from a file and creates an object. You can then assign this object to any of the templates in a DataList control.
The following code uses the Page_Load event handler to load a template created as shown above and named NewTemplate.ascx.
Protected Sub Page_Init(ByVal Sender As System.Object, _ ByVal e As System.EventArgs) If (Not Page.IsPostBack) Then DataList1.AlternatingItemTemplate = _ Page.LoadTemplate("NewTemplate.ascx") End If End Sub