4

我使用这篇http://blogs.msdn.com/b/mikeormond/archive/2008/07/26/dynamically-loading-listview-templates.aspx文章作为动态加载模板的示例(来自 .ascx 文件)。

这是作者代码:

     protected void Page_Load(object sender, EventArgs e)
    {

        ListView1.LayoutCreated += new EventHandler(ListView1_LayoutCreated);
        ListView1.LayoutTemplate = LoadTemplate("LayoutTemplate.ascx");
        ListView1.ItemTemplate = LoadTemplate("ItemTemplate.ascx");
    }

    void ListView1_LayoutCreated(object sender, EventArgs e)
    {
        //remove the layout template
        ListView1.Controls.RemoveAt(0);

        //recreate it
        Control newLayoutContainer = new Control();
        ListView1.LayoutTemplate.InstantiateIn(newLayoutContainer);
        var userControl = newLayoutContainer.Controls[0];
        userControl.ID = "MyLayout";
        ListView1.Controls.Add(newLayoutContainer);
    }

它给出了错误:

必须在 ListView 'ListView1' 上定义 ItemTemplate。

回发后。

怎么了?我应该在每次回发 ( http://forums.asp.net/p/1305569/2558209.aspx ) 时创建 ListView 吗?

4

1 回答 1

4

要解决您的问题,请执行以下操作:

<script runat="server">

   protected void ListView_Init(object sender, EventArgs e)
    {

         ListView1.ItemTemplate = LoadTemplate("ItemTemplate2.ascx");

    }

</script>

<asp:ListView ....   OnInit="ListView_Init">
于 2012-10-17T23:08:29.283 回答