Imports System.Data.SqlClient ’引用SqlClient命名空间 Public Class Form1 Const Connection String As String = "integrated security=sspi;initial catalog=Pubs; data source=(local)" ’定义连接字符串 Private Sub Button1_Click(By Val sender As Object, By Val e As System.EventArgs) Handles Button1.Click Dim cn As New SqlConnection (Connection String) Cn. Open() ’建立同数据库的连接 Dim ds As New Dataset("Book Sales") ’创建Dataset对象 Dim Titles Table As New Data Table("Titles") ds.Tables.Add(Titles Table) ’创建Data Table对象(Titles表),加入Dataset Dim GetTitlesString As String = "Select * From Titles" Dim da As New SqlDataAdapter(GetTitlesString, cn) da.Fill(Titles Table) ’填充Data Table da.Dispose() Dim Sales Table As New Data Table("Sales") ds.Tables.Add(Sales Table) Dim GetSalesString As String = "Select * From Sales" da = New SqlDataAdapter(GetSalesString, cn) da.Fill(Sales Table) ’创建并填充Sales表 da.Dispose() cn.Close() Dim relation As New Data Relation("Title Sales", TitlesTable.Columns("title_id"),SalesTable.Columns("title_id")) ds.Relations.Add(relation) 根据title_id列建立两个表的关联 DataGrid1.DataSource = ds 将DataGrid1绑定到Dataset对象(即ds) End Sub End Class |
(图1:Data Grid中装入两张表) |
(图2:主表情况) |
(图3:从表情况) |
(图4:窗体布局) |
Imports System.Data.SqlClient Public Class Form1 Const Connection String As String = "integrated security=sspi;initial catalog=pubs; data source=(local)" Private Sub Button1_Click(By Val sender As Object, By Val e As System.EventArgs) Handles Button1.Click Dim cn As New SqlConnection(Connection String) cn.Open() Dim ds As New Dataset Dim GetTitlesString As String = "Select * From Titles" Dim Titles Table As New Data Table("Titles") ds.Tables.Add(Titles Table) Dim da As New SqlDataAdapter(GetTitlesString, cn) da.Fill(Titles Table) da.Dispose() cn.Close() DataGrid1.DataSource = Titles Table ’主表显示在DataGrid1中 End Sub Private Sub DataGrid1_CurrentCellChanged(By Val sender As Object, By Val e As System.EventArgs) Handles DataGrid1.CurrentCellChanged Dim titled As String = DataGrid1.Item(DataGrid1.CurrentCell.RowNumber, 0).To String ’判断用户在主表中选择了哪一行,取出它的第0列(在本例中即为title_id列) Dim sql As String = "select * from sales where title_id=’" & titled & "’" ’SQL命令字符串,选择与主表中相同title_id值的从表数据 Dim cn As New SqlConnection(Connection String) cn.Open() Dim ds As New Dataset Dim da As New SqlDataAdapter(sql, cn) Dim Sales Table As New Data Table("Sales") ds.Tables.Add(Sales Table) da.Fill(Sales Table) ’用选择的从表数据填充,更新 da.Dispose() cn.Close() DataGrid2.DataSource = Sales Table End Sub End Class |
(图5:主从数据表同时显示) |