原理:前台两个 DataList 的嵌套
<!-- 放置DataList数据控件 -->
<asp:DataList ID="ParentCaption" runat="server" RepeatDirection="Vertical" onitemdatabound="ParentCaption_ItemDataBound">
<ItemTemplate>
<div style=" height:20px; width:185px; background-color:#f0f0f0;font-weight:bold; ">
[ <%# Eval("Type_Name")%> ]
</div>
<!-- 子标题 -->
<asp:DataList ID="SonCaption" runat="server" RepeatDirection="Horizontal" RepeatColumns="2">
<ItemTemplate>
<div style="margin-left:20px; list-style-type:none;">
<a href='<%# "SortBooks.aspx?TypeID="+Eval("Type_ID") %> '>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Type_Name")%> '></asp:Label> </a>
</div>
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
</asp:DataList>
<!-- 放置DataList数据控件 -->
后台对两个 DataList 进行绑定:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindParentType();
}
}
private void bindParentType()
{
DataSet ds = new DataSet();
if (this.Cache["Type_Name"] == null)
{
BLL.BookCategory bookType = new BLL.BookCategory();
ds = bookType.GetList("");
this.Cache.Insert("Type_Name", ds, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
}
else
{
ds = (DataSet)this.Cache["Type_Name"];
}
DataRow[] darow = ds.Tables[0].Select(" Type_FatherTypeID is null");
DataTable dt = ds.Tables[0].Clone();
foreach (DataRow dr in darow)
{
dt.ImportRow(dr);
}
this.ParentCaption.DataSource = dt;
this.ParentCaption.DataKeyField = "Type_ID";
this.ParentCaption.DataBind();
}
//在父级 DataList 内找子级 DataList 控件
protected void ParentCaption_ItemDataBound(object sender, DataListItemEventArgs e)
{
DataList dl2 = (DataList)e.Item.FindControl("SonCaption");
int parentID = Convert.ToInt32(this.ParentCaption.DataKeys[e.Item.ItemIndex].ToString());
DataSet ds = (DataSet)this.Cache["Type_Name"];
DataRow[] dro = ds.Tables[0].Select(" Type_FatherTypeID=" + parentID);
DataTable dt = ds.Tables[0].Clone();
foreach (DataRow dr in dro)
{
dt.ImportRow(dr);
}
dl2.DataSource = dt;
dl2.DataBind();
}