Dim
dsOrdersAndDetails
As
New
DataSet
()
'两个SqlDataAdapter,一个用来读取Orders表,
'一个用来读取Order Details表
Dim
daOrders
As
New
SqlClient.
SqlDataAdapter
()
Dim
daDetails
As
New
SqlClient.
SqlDataAdapter
()
'数据库连接
Dim
conn
As
New
SqlClient.
SqlConnection
()
'建立两个数据表,一个代表Orders表,
'一个代表OrderDetails表
Dim
tblOrders
As
New
DataTable
()
Dim
tblDetails
As
New
DataTable
()
'把两个数据表加入到数据集中
dsOrdersAndDetails.Tables.Add(tblOrders)
dsOrdersAndDetails.Tables.Add(tblDetails)
'设置数据库连接字符串
conn.ConnectionString =
"Data Source=(local);Initial Catalog=wb2012;Integrated Security=SSPI"
'设置读取数据的SQL命令
daOrders.SelectCommand =
New
SqlClient.
SqlCommand
(
"Select * From Fi_mCustomer"
, conn)
daDetails.SelectCommand =
New
SqlClient.
SqlCommand
(
"Select * From [Fi_Customer]"
, conn)
'打开数据库连接,填充两个数据表
conn.Open()
daOrders.Fill(tblOrders)
daDetails.Fill(tblDetails)
conn.Close()
'开始建立两个数据表之间的关联
'必须在数据表被填充以后建立关联,因为在那以前,两个数据表都是空的
'关联也无从谈起
Dim
rltOrdersToDetails
As
DataRelation
'第一个参数是关联的名字,就像Case7_5中的OrdersOrder_x0020_Details
'第二个参数是主子段,也就是主表中的OrderID
'第三个参数是从字段,也就是从表中的OrderID
rltOrdersToDetails =
New
DataRelation
(
"Orders_To_Details"
, _
tblOrders.Columns(
"cid"
), _
tblDetails.Columns(
"cid"
))
'把建立好的关联加入数据集
dsOrdersAndDetails.Relations.Add(rltOrdersToDetails)
Me
.DataGridView1.DataSource = tblOrders
Me
.DataGridView2.DataSource = tblOrders
Me
.DataGridView2.DataMember =
"Orders_To_Details"