
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<HTML>
	<HEAD>
		<title>使用DataRelation类创建关系并利用父/子关系读取数据示例</title>
		
		<script language=C# runat=server>
		
			void Page_Load(object sender, System.EventArgs e)
			{
				// 连接字符串和 SQL 语句
				string ConnString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
				string Sql = "SELECT * FROM Customers; SELECT * FROM Orders";

				// 创建 Connection 和 DataAdapter 对象
				SqlConnection myConn = new SqlConnection(ConnString);
				SqlDataAdapter sqlAdapter = new SqlDataAdapter(Sql, myConn);

				// 填充数据
				DataSet dataSet = new DataSet();
				sqlAdapter.Fill(dataSet, "Table");

				// 命名表名
				dataSet.Tables[0].TableName = "Customers";
				dataSet.Tables[1].TableName = "Orders";
			
				// 创建 Customers 和 Orders 的父/子表关系
				dataSet.Relations.Add("CustomersOrders", dataSet.Tables["Customers"].Columns["CustomerID"],
					dataSet.Tables["Orders"].Columns["CustomerID"]);

				// 使用 GetChildRows() 方法遍历子行
				foreach(DataRow custRow in dataSet.Tables["Customers"].Rows)
				{
					myLabel.Text += "<b>Parent Row: " + custRow["CustomerID"] + "&nbsp;&nbsp;" + custRow["CompanyName"] + "</b><br>";
					myLabel.Text += "Child Row: <br>";
					foreach(DataRow orderRow in custRow.GetChildRows("CustomersOrders"))
					{
						myLabel.Text += "&nbsp;&nbsp;&nbsp;&nbsp; " + orderRow["OrderID"] + "&nbsp;&nbsp;" + orderRow["EmployeeID"] + "<br>";
					}
				}
			}
			
		</script>
		
	</HEAD>
	<body>
		<form id="Form1" method="post" runat="server">
			<h3>使用DataRelation类创建关系并利用父/子关系读取数据示例</h3>
			<asp:Label id="myLabel" runat="server"></asp:Label>
		</form>
	</body>
</HTML>
