把两个表的数据都读出来,建立两个表的关系
ds.Relation.Add();
然后在父Repeater的ItemDataBind事件中找到子Repeater
再根据关系找到子Repeater对应的数据源,绑定上ok。
页面上:
<asp:Repeater id="Repeater1" runat="server">
<HeaderTemplate>
<table width="500">
<tr bgcolor=blue>
<td>用户留言显示</td>
</tr>
</HeaderTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
<ItemTemplate>
<tr bgcolor=aaaaaa>
<td>用户名:<%#DataBinder.Eval(Container.DataItem,"username")%></td>
</tr>
<tr>
<td>用户留言的显示</td>
</tr>
<tr>
<td><asp:Repeater id="Repeater2" runat="server">
<ItemTemplate>
留言信息<%#DataBinder.Eval(Container.DataItem,"content")%><br>
</ItemTemplate>
</asp:Repeater></td>
</tr>
</ItemTemplate>
</asp:Repeater>
cs代码:
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace AdoDotNet_Demo { /// <summary> /// RepeaterLink1 的摘要说明。 /// </summary> public class RepeaterLink1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Repeater Repeater2; protected System.Web.UI.WebControls.Repeater Repeater1; private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 if (!Page.IsPostBack) { string strconn = "server=.;uid=sa; pwd=;database=myweb"; SqlConnection conn = new SqlConnection(strconn); SqlDataAdapter da = new SqlDataAdapter("select * from userinfo", conn); DataSet ds = new DataSet(); da.Fill(ds, "user"); SqlDataAdapter da1 = new SqlDataAdapter("select * from content", conn); da1.Fill(ds, "content"); ds.Relations.Add("relation1", ds.Tables["user"].Columns["UserName"], ds.Tables["content"].Columns["UserName"]); Repeater1.DataSource = ds.Tables["user"]; Repeater1.DataBind(); } } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.Repeater1.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.Repeater1_ItemDataBound); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Repeater1_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item) { //repeater1行数据获得到 DataRowView drv = (DataRowView)e.Item.DataItem; DataView dv = drv.CreateChildView("relation1"); //根据行数据得到repeater2的数据源 //找到当前行中repeater2 System.Web.UI.WebControls.Repeater r = (System.Web.UI.WebControls.Repeater)e.Item.FindControl("Repeater2"); r.DataSource = dv; r.DataBind(); } } } }