我建議有2箇中繼器。外將綁定到一個月列表和一個月內內的所有條目:
<asp:Repeater ID="MonthList" runat="server" OnItemDataBound="MonthList_ItemDataBound">
<ItemTemplate>
<h2><%# Container.DataItem %></h2>
<asp:Repeater ID="ItemList" runat="server">
<ItemTemplate><%# Eval("Name") %></ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
對於這個標記後面的代碼可能看起來像:
public partial class _Default : System.Web.UI.Page
{
public class Entry
{
public string Month {get;set;}
public string Name {get;set;}
}
List<Entry> entries = new List<Entry>()
{
new Entry() { Month = "Jan", Name = "name1"},
new Entry() { Month = "Jan", Name = "name2"},
new Entry() { Month = "Feb", Name = "name3"},
new Entry() { Month = "Aug", Name = "name4"},
new Entry() { Month = "Dec", Name = "name5"},
new Entry() { Month = "Dec", Name = "name6"}
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MonthList.DataSource = entries.GroupBy(x => x.Month).Select(x => x.Key);
MonthList.DataBind();
}
}
protected void MonthList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var itemList = (Repeater)e.Item.FindControl("ItemList");
var month = (string)e.Item.DataItem;
itemList.DataSource = entries.Where(x => x.Month == month);
itemList.DataBind();
}
}
}
我用內存中的集合的樣本和LINQ將其轉換。首先,我們按月分組數據源。然後,在MonthList_ItemDataBound中,對於每個被綁定的月份,我們查找內部中繼器並將其與通過當前(DataItem)月份過濾的集合綁定。希望這可以幫助。
難道你不同時從數據庫中選擇?或者甚至在給該中繼器提供數據源時? – 2011-03-30 05:39:00