Partilhar via


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

  1. Create a new text file with an .ascx extension.

  2. 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-bound Label controls. 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 the LoadTemplate method. This method reads a template definition from a file and creates an ITemplate object. You can then assign this object to any of the templates in a DataList control.

    The following example uses the Page_Init 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)
        DataList1.AlternatingItemTemplate = _
            Page.LoadTemplate("NewTemplate.ascx")
    End Sub
    
    protected void Page_Init(object sender, EventArgs e)
    {
        DataList1.AlternatingItemTemplate = 
            Page.LoadTemplate("NewTemplate.ascx");
    }
    

See Also

Reference

DataList Web Server Control Overview