Hallo Rolf,
wenn man sich die Relation über eine BindingSource zunutze macht, funktioniert es ohne manuelle Eingriffe.
Eine BindingSource kann selbst als Datenquelle dienen und über eine DataRelation auf die
untergeordneten DataTable gefiltert zugreifen.
Ein Beispiel für die Northwind Customers = > Orders, dass sich hier auf zwei DataGridViews beschränkt:
Imports System.Data
Imports System.Data.Common
Imports System.Data.SqlClient
Public Class CustomerOrderForm
Dim formDataSet As DataSet
Private Sub CustomerOrderForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.formDataSet = GetDataSet()
Dim customerBindingSource = New BindingSource(Me.formDataSet, "Customers")
' Abhängige BindingSource über Relation
Dim ordersBindingSource = New BindingSource(customerBindingSource, "CustomerOrderRelation")
' Zwei Grid
Me.customerDataGridView.DataSource = customerBindingSource
Me.orderDataGridView.DataSource = ordersBindingSource
End Sub
Public Function GetDataSet() As DataSet
Dim ds = GetDataSet( _
"SELECT * FROM dbo.Customers; SELECT * FROM dbo.Orders;", _
"Customers", "Orders")
' Relation hinzufügen für BindingSource verwendet.
ds.Relations.Add("CustomerOrderRelation", _
ds.Tables("Customers").Columns("CustomerID"), _
ds.Tables("Orders").Columns("CustomerID"), _
True)
With ds.Tables("Orders").Columns("OrderID")
.AutoIncrement = True
.AutoIncrementSeed = -1
.AutoIncrementStep = -1
End With
Return ds
End Function
Public Shared Function GetDataSet( _
ByVal commandText As String, _
ByVal ParamArray tableNames As String()) As DataSet
Using adapter As New SqlDataAdapter(New SqlCommand( _
commandText, _
New SqlConnection(My.Settings.NorthwindConnectionString)))
' Tabellenzuordnung
If tableNames IsNot Nothing AndAlso tableNames.Length > 0 Then
For tableIndex As Integer = 0 To tableNames.Length - 1
If tableIndex = 0 Then
adapter.TableMappings.Add("Table", tableNames(0))
Else
adapter.TableMappings.Add("Table" & tableIndex.ToString(), tableNames(tableIndex))
End If
Next
End If
Dim dataSet As New DataSet()
adapter.Fill(dataSet)
Return dataSet
End Using
End Function
End Class
Das GetDataSet ist als eine Spielerei zu verstehen (in Reminiszenz an den anderen Beitrag ;-).
In Verbindung mit einem typisierten DataSet wäre das auch zur Entwurfszeit einstellbar.
Gruß Elmar