DataSet中DataGridView父子表联动绑定及SqlClient加载错误求助
问题解决方案
一、实现DataGridView父子表联动
你的代码已创建DataSet表关系,但直接绑定数据表无法实现联动,需通过BindingSource结合父行的子数据关联逻辑完成。修改后的完整代码如下:
Dim SQL1 As String = "Select * From Table1" Dim SQL2 As String = "Select * from Table2" Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=HeatsListDB.accdb" Dim OleDBConn1 As OleDbConnection = New OleDbConnection(ConnString) Dim DS1 As New DataSet Dim DA1 As OleDbDataAdapter = New OleDbDataAdapter(SQL1, OleDBConn1) Dim DA2 As OleDbDataAdapter = New OleDbDataAdapter(SQL2, OleDBConn1) ' DataAdapter.Fill会自动处理连接的打开/关闭,无需手动操作 DA1.Fill(DS1, "Table1") DA2.Fill(DS1, "Table2") ' 建立表关联(确保Field1是两张表的关联主键/外键) Dim Relation As New DataRelation("Relation1", DS1.Tables("Table1").Columns("Field1"), DS1.Tables("Table2").Columns("Field1")) DS1.Relations.Add(Relation) ' 使用BindingSource绑定父表,提升数据操作灵活性 Dim parentBS As New BindingSource() parentBS.DataSource = DS1 parentBS.DataMember = "Table1" Me.dg1.DataSource = parentBS ' 父表行切换时触发子表数据更新 Private Sub dg1_SelectionChanged(sender As Object, e As EventArgs) Handles dg1.SelectionChanged If dg1.CurrentRow IsNot Nothing Then Dim currentRow As DataRowView = DirectCast(dg1.CurrentRow.DataBoundItem, DataRowView) ' 获取当前父行对应的所有子数据 Dim childRows As DataRow() = currentRow.Row.GetChildRows("Relation1") ' 克隆子表结构并导入关联数据,再绑定到子DataGridView Dim childTable As DataTable = DS1.Tables("Table2").Clone() For Each row In childRows childTable.ImportRow(row) Next Me.dg2.DataSource = childTable End If End Sub
关键说明:
- 用
BindingSource绑定父表,更适配WinForms的数据绑定机制 - 通过
SelectionChanged事件监听父表行切换,调用GetChildRows获取关联子数据 - 无需手动管理OleDbConnection的开闭,
DataAdapter.Fill方法会自动处理
二、解决"Could not load file or Assembly 'Microsoft.Data.SqlClient, Version=3.0.0.0'"错误
你当前使用OleDb连接Access数据库,报错SqlClient说明项目中存在依赖旧版本该程序集的组件,按以下步骤排查:
检查NuGet依赖
- 右键项目→管理NuGet程序包,确认
Microsoft.Data.SqlClient已安装且版本为5.0.0.0 - 检查其他引用的第三方库是否依赖旧版本SqlClient,尝试将这些库更新至最新版
- 右键项目→管理NuGet程序包,确认
添加程序集绑定重定向
在项目的App.config中添加配置,强制使用已安装的5.0.0.0版本:<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.Data.SqlClient" publicKeyToken="23ec7fc2d6eaa4a5" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>清理重建项目
- 右键项目→清理
- 删除项目目录下的
bin和obj文件夹 - 重新编译项目
确认引用属性
右键项目中的Microsoft.Data.SqlClient引用→属性,将"复制本地"设置为True,确保程序集被复制到输出目录
内容的提问来源于stack exchange,提问作者Gary Wheeler
相关产品推荐
相关产品推荐

