来自.ascx的动态加载ListView模板

时间:2012-10-15 21:49:51

标签: asp.net listview itemtemplate

我使用此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。

回发后。

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

1 个答案:

答案 0 :(得分:4)

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

<script runat="server">

   protected void ListView_Init(object sender, EventArgs e)
    {

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

    }

</script>

<asp:ListView ....   OnInit="ListView_Init">