How to: dynamically create a template in the datalist Web Server Control
The template does not need to be allocated during design. In some cases, you may be able to layout templates at design time, but you know that the changes made at runtime are so extensive that loading new templates at runtime can simplify programming. In other cases, there may be several possible templates, but you need to change the template at runtime.
Create a template definition file
Create a new text file using the. ascx extension.
Add template definition statements to the template file and save the statements (the tags used should be the same as those used in all declarative templates ).
The following example shows the content of A. ascx file with template tags. The template contains the data binding label control. Data Binding will be boundDatalistControl data source for parsing.
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>
Dynamic template Creation
Add code to the web forms page to use the loadtemplate method to load the template. This method reads the template definition from the file and creates an itemplate object. Then you can allocate this objectDatalistAny template in the control.
Use the following codePage_loadThe event handler loads the template named newtemplate. ascx created in the preceding process.
Visual BasicProtected 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
C #protected void Page_Init(object sender, EventArgs e)
{
DataList1.AlternatingItemTemplate =
Page.LoadTemplate("NewTemplate.ascx");
}
See references
Overview of datalist web server controls