实现效果如下图:
前台代码:
Code
<div>
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table width="100%" border="0" cellpadding="0" cellspacing="0"></table>
</HeaderTemplate>
<ItemTemplate>
<!--分类名称-->
<tr>
<td><%#Eval("cate_name") %>
<br />
</td>
</tr>
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<tr>
<td> <%#Eval("proc_name")%> <br />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
<br />
</ItemTemplate>
<AlternatingItemTemplate>
<tr>
<td><%#Eval("cate_name") %>
</td>
</tr>
</AlternatingItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
this.Repeater1.DataSource = DataBind();
this.Repeater1.DataBind();
}
/**//// <summary>
///类别的数据源
/// </summary>
public DataSet DataBind()
{
string Connstring = "server=.;database=temptest;uid=sa;pwd=sa;";
string sqlStr = "select * from Categories";
using (SqlConnection con = new SqlConnection(Connstring))
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con);
DataSet ds = new DataSet();
sda.Fill(ds, "Category");
return ds;
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater rptProduct = (Repeater)e.Item.FindControl("Repeater2");
if (rptProduct != null)
{
//找到分类 Repeater关联的数据项
DataRowView rowv = (DataRowView)e.Item.DataItem;
//提取分类ID
int Cate_id = Convert.ToInt32(rowv["cate_id"]);
//根据分类ID来获取分类下的产品,并绑定产品Repeater2
rptProduct.DataSource = DataBind(Cate_id);
rptProduct.DataBind();
}
}
}
/**//// <summary>
///类别下产品的数据源
/// </summary>
public DataSet DataBind(int category)
{
string Connstring = "server=.;database=temptest;uid=sa;pwd=sa;";
string sqlStr = "select * from Procducts where cate_id=@cate_id";
using (SqlConnection con = new SqlConnection(Connstring))
{
con.Open();
SqlCommand cmd = new SqlCommand(sqlStr, con);
cmd.Parameters.Add(new SqlParameter("@cate_id", category));
SqlDataAdapter sda = new SqlDataAdapter(sqlStr,con);
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds, "Procutes");
return ds;
}
}
数据库文档:
create database temptest
go
create table Categories
(
cate_id int not null,
cate_name varchar(20) not null
)
create table Procducts
(
porc_id int not null,
cate_id int not null,
proc_name varchar(20) not null
)
insert into Categories values(1,'数码')
insert into Categories values(2,'书籍')
insert into Procducts values(1,1,'笔记本')
insert into Procducts values(2,1,'数码相机')
insert into Procducts values(3,1,'手机')
insert into Procducts values(4,1,'PSP')
insert into Procducts values(5,1,'360xbox')
insert into Procducts values(6,2,'Asp.net C#')
insert into Procducts values(7,2,'VB')
insert into Procducts values(8,2,'Jave')
insert into Procducts values(9,2,'PHP')
insert into Procducts values(10,2,'Ruby')