本文介紹了一種利用Repeater控件顯示主-從關系數據表的方法。
原文參見:http://support.microsoft.com/default.ASPx?scid=kb;en-us;306154
NestedRepeater.ASPx
<%@ Import Namespace="System.Data" %>
<%@ Page language="<a href="http://dev.21tx.com/dotnet/csharp/" target="_blank">C#</a>" Codebehind="NestedRepeater.ASPx.cs"
AutoEventWireup="false" Inherits="eMeng.NestedRepeater" %>
<Html>
<body>
<form runat="server">
<!-- 父Repeater開始 -->
<ASP:repeater id="parentRepeater" runat="server">
<itemtemplate>
<b>
<%# DataBinder.Eval(Container.DataItem,"au_id") %>
</b>
<br>
<!-- 子Repeater開始 -->
<ASP:repeater id="childRepeater" runat="server"
datasource='<%# ((DataRowVIEw)Container.DataItem).Row.GetChildRows("myrelation") %>'>
<itemtemplate>
<%# DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%>
<br>
</itemtemplate>
</ASP:repeater>
<!-- 子Repeater結束 -->
</itemtemplate>
</ASP:repeater>
<!-- 父Repeater結束 -->
</form>
</body>
</Html>
NestedRepeater.ASPx.cs
using System;
using System.Data;
using System.Data.SqlClIEnt;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace eMeng
{
/// <summary>
/// NestedRepeater 的摘要說明。
/// 本文介紹如何利用Repeater控件顯示主-從關系的表格
/// 原文參見:
/// http://support.microsoft.com/default.ASPx?scid=kb;en-us;306154
/// </summary>
public class NestedRepeater : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Repeater parentRepeater;
public void Page_Load(object sender, EventArgs e)
{
// 為Authors表創建 Connection 和 DataAdapter
string cnnString = @"server=(local)\NetSDK;database=pubs; Integrated Security=SSPI;";
SqlConnection cnn = new SqlConnection(cnnString);
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from authors",cnn);
//創建填充 DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds,"authors");
// 為Titles表創建 DataAdapter
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from titleauthor",cnn);
cmd2.Fill(ds,"titles");
// 創建 Authors 表和 Titles 表之間的關系.
ds.Relations.Add("myrelation",
ds.Tables["authors"].Columns["au_id"],
ds.Tables["titles"].Columns["au_id"]);
// 綁定Authors到父Repeater
parentRepeater.DataSource = ds.Tables["authors"];
Page.DataBind();
cnn.Close();
cnn.Dispose();
}
private void Page_Init(object sender, EventArgs e)
{
InitializeComponent();
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
public NestedRepeater()
{
Page.Init += new System.EventHandler(Page_Init);
}
}
}