ADO.NET嵌套数据绑定
自动获取数据库中的主从关系数据,以下是获取省份及省份对应的城市,代码如下:
重点:DataSource ='<%#Getawd(Eval("pid").ToString()) %>' 调用GetCity方法获取子类
实现效果如下:
方法二:在第一个Repeater的ItemDataBound事件中绑定第二个Repeater,HTML代码中第一个Repeater不赋予DataSource
<asp:repeater ID="Repeater1" runat="server">
<ItemTemplate >
<span style ="font-weight :bold "><%#Eval ("pname") %></span>
<ul>
<asp:Repeater ID="detal" runat ="server" DataSource ='<%#GetCity(Eval("pid").ToString()) %>'>
<ItemTemplate >
<li><%#Eval("city_name") %></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</ItemTemplate>
</asp:repeater>
<ItemTemplate >
<span style ="font-weight :bold "><%#Eval ("pname") %></span>
<ul>
<asp:Repeater ID="detal" runat ="server" DataSource ='<%#GetCity(Eval("pid").ToString()) %>'>
<ItemTemplate >
<li><%#Eval("city_name") %></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</ItemTemplate>
</asp:repeater>
重点:DataSource ='<%#Getawd(Eval("pid").ToString()) %>' 调用GetCity方法获取子类
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindGrid();
}
//获取大类的类别
protected void BindGrid()
{
string cmdText = "select pid, pname from pro";
DataTable dt = vc.GetDataTable(cmdText );
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
//获取小类内容
protected DataTable GetCity(string id)
{
string cmdText = "select city_name from city where promo_id = " + id + "";
DataTable dt = vc.GetDataTable(cmdText);
return dt;
}
{
if (!Page.IsPostBack)
BindGrid();
}
//获取大类的类别
protected void BindGrid()
{
string cmdText = "select pid, pname from pro";
DataTable dt = vc.GetDataTable(cmdText );
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
//获取小类内容
protected DataTable GetCity(string id)
{
string cmdText = "select city_name from city where promo_id = " + id + "";
DataTable dt = vc.GetDataTable(cmdText);
return dt;
}
实现效果如下:
方法二:在第一个Repeater的ItemDataBound事件中绑定第二个Repeater,HTML代码中第一个Repeater不赋予DataSource
protected void repeatTitle_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataRowView dr = (DataRowView)e.Item.DataItem;
DataTable mydt = GetCity(dr[0].ToString());
if (mydt.Rows.Count > 0)
{
Repeater myRepeat = (Repeater)e.Item.FindControl("repeatCont");
myRepeat.DataSource = mydt;
myRepeat.DataBind();
mydt.Dispose();
}
else
{
e.Item.Visible = false; //没有数据时不显示
}
}
{
DataRowView dr = (DataRowView)e.Item.DataItem;
DataTable mydt = GetCity(dr[0].ToString());
if (mydt.Rows.Count > 0)
{
Repeater myRepeat = (Repeater)e.Item.FindControl("repeatCont");
myRepeat.DataSource = mydt;
myRepeat.DataBind();
mydt.Dispose();
}
else
{
e.Item.Visible = false; //没有数据时不显示
}
}