开发者

ListView: Display data divided into groups?

I would like to display the contents of a DataTable, divided into several groups depending on the value of one of the columns. So, if I have a DataTable (from SQL query) with:

GroupID   Name   Description
1         foo    bar
1         one    two
2         some   thing

I开发者_JS百科 would like to place all records containing GroupID 1 in one div, all records with GroupID 2 in another div, and so on. How can I do this?

I'm writing in ASP.NET 4.0, with C# codebehind.


You can use LINQ to DataSet to group your data before databinding. Something along the lines of

var query = from row in myDataTable.AsEnumerable()
            group row by row["GroupID"] // appropriate column access code here
            select row;

Then you'll need nested ListViews (code blatantly copied from here) to actually render it. Something along the lines of

<asp:ListView runat="server" ID="outer" ItemPlaceholderID="PlaceHolder2">
    <LayoutTemplate>
        <asp:PlaceHolder runat="server" ID="PlaceHolder2" /> 
    </LayoutTemplate>

    <ItemTemplate>
        <h1>[Some heading if you'd like one]</h1>

        <asp:ListView runat="server" ID="inner"
          ItemPlaceholderID="PlaceHolder3"
          DataSource="<%# Container.DataItem %>">
          <LayoutTemplate>
            <ul>
              <asp:PlaceHolder runat="server" ID="PlaceHolder3" /> 
            </ul>
          </LayoutTemplate>
          <ItemTemplate>
            <!-- data goes here -->
          </ItemTemplate>
      </asp:ListView>
  </ItemTemplate>
</asp:ListView>


foreach(DataRow r in myDataTable.Filter("GroupID = 1"))
{
    //write out contents of div1
}

foreach(DataRow r in myDataTable.Filter("GroupID = 2"))
{
    //write out contents of div2
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜