扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
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:主从数据表同时显示) |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者