|
這個(gè)問題,平時(shí)很少看到,一般在數(shù)據(jù)綁定之前,數(shù)據(jù)都是放在一個(gè)表中的,實(shí)際上,如果表之間存在關(guān)系,綁定多個(gè)表也是可以的。下面就是 DataSet中兩個(gè)表進(jìn)行綁定的例子。
復(fù)制代碼 代碼如下:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser");
System.Data.DataRow dr;
dataTable1.Columns.Add(new System.Data.DataColumn("UserId", typeof(System.Int32)));
dataTable1.Columns.Add(new System.Data.DataColumn("UserName", typeof(System.String)));
dataTable1.PrimaryKey = new System.Data.DataColumn[] { dataTable1.Columns["UserId"] };
for (int i = 0; i < 8; i++)
{
dr = dataTable1.NewRow();
dr[0] = i;
dr[1] = "【孟子E章】" + i.ToString();
dataTable1.Rows.Add(dr);
}
System.Data.DataTable dataTable2 = new System.Data.DataTable("BlogArticle");
dataTable2.Columns.Add(new System.Data.DataColumn("ArticleId", typeof(System.Int32)));
dataTable2.Columns.Add(new System.Data.DataColumn("Title", typeof(System.String)));
dataTable2.Columns.Add(new System.Data.DataColumn("UserId", typeof(System.Int32)));
dataTable2.PrimaryKey = new System.Data.DataColumn[] { dataTable1.Columns["ArticleId"] };
Random rd = new Random();
for (int i = 0; i < 20; i++)
{
dr = dataTable2.NewRow();
dr[0] = i;
dr[1] = "文章標(biāo)題" + i.ToString();
dr[2] = rd.Next(0, 7);
dataTable2.Rows.Add(dr);
}
ds.Tables.Add(dataTable1);
ds.Tables.Add(dataTable2);
System.Data.DataColumn parentColumn = ds.Tables["BlogUser"].Columns["UserId"];
System.Data.DataColumn childColumn = ds.Tables["BlogArticle"].Columns["UserId"];
System.Data.DataRelation user_article = new System.Data.DataRelation("UserId", parentColumn, childColumn);
ds.Relations.Add(user_article);
this.Repeater1.DataSource = ds.Tables["BlogArticle"].DefaultView;
this.Repeater1.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title> ASP.NET 綁定DataSet中的多個(gè)表 作者:孟子E章</title>
</head>
<body>
<form id="form1" runat="server">
<ASP:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1">
<tr style="background:orange">
<th>文章標(biāo)題</th>
<th>用戶ID</th>
<th>用戶名</th>
</tr>
</HeaderTemplate>
<FooterTemplate>
</table></FooterTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("Title")%></td><td><%#Eval("UserId") %></td>
<td><%#(Container.DataItem as System.Data.DataRowView).Row.GetParentRow("UserId")["UserName"]%>
</td>
</tr>
</ItemTemplate>
</ASP:Repeater>
</form>
</body>
</html>
AspNet技術(shù):ASP.NET 綁定DataSet中的多個(gè)表,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。