这个问题,平时很少看到,一般在数据绑定之前,数据都是放在一个表中的,实际上,如果表之间存在关系,绑定多个表也是可以的。下面就是 DataSet中两个表进行绑定的例子。
代码如下:
/p>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
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] = "文章标题" + 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();
}
ASP.NET 绑定DataSet中的多个表 作者:孟子E章文章标题 | 用户ID | 用户名 |
---|