[转]在 DataList Web 服务器控件中动态创建模板

模板不必在设计时进行分配。在某些情况下,可能能够在设计时布局模板,但是知道在运行时所做的更改非常广泛,以至于在运行时加载新的模板反而可简化编程。在其他情况下,可能有几个可能的模板,但要在运行时更改模板。

策略之一是创建其中带有基本模板布局的模板文件,即模板定义文件。若要在运行时加载模板,请使用 Page.LoadTemplate 方法。此方法从文件中读取模板定义,并创建 ITemplate 接口对象。然后可将此对象分配到 DataList 中的任何模板。

创建模板定义文件

  1. 在“项目”菜单上单击“添加新项”。
  2. 在“添加新项”对话框中,选择“文本文件”。将该文件命名为带有“.ascx”扩展名。
  3. 将模板定义语句添加到该模板文件中,然后保存它。

    下面列出的内容创建一个模板,它显示字符串“Name:”,后面跟有绑定到 DataList 的数据源的“LastName”字段。

    <!-- Visual Basic -->
    <%@ Language = "VB" %>
    Name: 
    <b> <%# DataBinder.Eval(Container, "DataItem.LastName"%> </b>

    <!-- Visual C# -->
    <%@ Language = "C#" %>
    Name: 
    <b> <%# DataBinder.Eval(Container, "DataItem.LastName"%> </b>

动态创建模板

  • 向 Web 窗体页中添加代码以使用 Page.LoadTemplate 方法加载模板。

    以下代码使用 Page_Load 事件处理程序来加载按上述过程创建的名称为 NewTemplate.ascx 的模板。

        
    ' Visual Basic 
    Private Function CreateDataSource() As DataTable
       
    Dim dt As DataTable = New DataTable()
       dt.Columns.Add(
    "LastName", Type.GetType("System.String"))
       dt.Rows.Add(
    New Object() {"Smith"})
       dt.Rows.Add(
    New Object() {"Jones"})
       dt.Rows.Add(
    New Object() {"Clark"})
       
    Return dt
    End Function

    Protected Sub Page_Init(ByVal Sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Init
       InitializeComponent()
       
    If (Not Page.IsPostBack) Then
          DataList1.AlternatingItemTemplate 
    = _
          Page.LoadTemplate(
    "NewTemplate.ascx")
       
    End If
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
       
    'Put user code to initialize the page here
       If (Not Page.IsPostBack) Then
          DataList1.DataSource 
    = CreateDataSource()
          DataList1.DataBind()
       
    End If
    End Sub
    // C#
    private DataTable CreateDataSource()
    {
       DataTable dt 
    = new DataTable();
       dt.Columns.Add(
    "LastName", Type.GetType("System.String"));
       dt.Rows.Add(
    new object[] {"Smith"});
       dt.Rows.Add(
    new object[] {"Jones"});
       dt.Rows.Add(
    new object[] {"Clark"});
       
    return dt;
    }

    private void Page_Init(object sender, EventArgs e)
    {
       InitializeComponent();
       DataList1.AlternatingItemTemplate 
    = 
       Page.LoadTemplate(
    "NewTemplate.ascx");
    }

    private void Page_Load(object sender, System.EventArgs e)
    {
       
    // Put user code to initialize the page here
       if (!Page.IsPostBack)
       {
          DataList1.DataSource 
    = CreateDataSource();
          DataList1.DataBind();
       }
    }

    原文:http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/vbcon/html/vbgrfcreatingtemplatecolumnsdynamicallyindatalistwebservercontrol.asp
原文地址:https://www.cnblogs.com/Bruce_H21/p/552114.html