More on Dynamically Loading ListView Templates

I got quite a few comments on my post on Dynamically Loading ListView Templates so rather than trying to paste code into a comment in reply, I thought I'd paste an update here. Specific issues raised were problems when databinding without a DataSource control and problems on postback. Here's a new version that addresses both those issues:

 <%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  
<html xmlns="https://www.w3.org/1999/xhtml">
<head id="Head1" runat="server"></head>
<body>
  <form id="form1" runat="server">

  <asp:ListView ID="ListView1" 
    runat="server" 
    ItemPlaceholderID="MyLayout$itemPlaceholder"
    OnLayoutCreated="ListView1_LayoutCreated">
  </asp:ListView>

  <asp:Button ID="Button1" runat="server" Text="I Do Postbacks" />

  </form>
</body>
</html>
 using System;
using System.Linq;
using System.Web.UI;
using System.Xml.Linq;

public partial class Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    XDocument xdoc = XDocument.Load(Server.MapPath("~/XmlFile.xml"));

    var query = from x in xdoc.Descendants("book")
                select new { id = (string)x.Attribute("id") };

    ListView1.DataSource = query;
    ListView1.DataBind();
  }

  protected void ListView1_LayoutCreated(object sender, EventArgs e)
  {
    ListView1.LayoutTemplate = LoadTemplate("WebUserControl.ascx");
    ListView1.ItemTemplate = LoadTemplate("WebUserControl2.ascx");

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

Hope that's useful.

Technorati Tags: asp.net,listview