如何将数据绑定到DataRelation?

How to bind data to DataRelation?

我有以下代码来创建两个绑定源。第一个填充了主人 table,第二个填充了基于关系的子 table。

    Dim DataSet As New DataSet
    Dim BindingSource1 As New BindingSource
    Dim BindingSource2 As New BindingSource

    Dim DataTable1 As DataTable = GetDT1()
    Dim DataTable2 As DataTable = GetDT2()

    DataSet.Tables.Add(DataTable1)
    DataSet.Tables.Add(DataTable2)

    Dim Rel As DataRelation = New DataRelation("R", DataSet.Tables("DT1").Columns("C1"), DataSet.Tables("DT2").Columns("C1"), True)
    DataSet.Relations.Add(Rel)

    BindingSource1.DataSource = DataSet
    BindingSource1.DataMember = "DT1"

    BindingSource2.DataSource = DataSet
    BindingSource2.DataMember = "R"

其中 GetDT1 和 GetDT2 如下:

Public Function GetDT1() As DataTable
    Dim DT As New DataTable("DT1")

    DT.Columns.Add(New DataColumn("C1"))

    Dim R As DataRow = DT.NewRow

    R("C1") = 1
    DT.Rows.Add(R)

    R = DT.NewRow
    R("C1") = 2
    DT.Rows.Add(R)

    R = DT.NewRow
    R("C1") = 3
    DT.Rows.Add(R)

    Return DT
End Function

Public Function GetDT2() As DataTable
    Dim DT As New DataTable("DT2")

    DT.Columns.Add(New DataColumn("C1"))
    DT.Columns.Add(New DataColumn("C2"))

    Dim R As DataRow = DT.NewRow

    R("C1") = 1
    R("C2") = "A"
    DT.Rows.Add(R)

    R = DT.NewRow
    R("C1") = 1
    R("C2") = "B"
    DT.Rows.Add(R)

    R = DT.NewRow
    R("C1") = 2
    R("C2") = "Coucou"
    DT.Rows.Add(R)

    Return DT
End Function

当我 运行 代码时,我在行中有一个错误:BindingSource2.DataMember = "R"。它说:

DataMember 属性 'R' 无法在 DataSource 上找到。

有人知道我的代码有什么问题吗?

干杯,

答案如下:

Dim DataSet As New DataSet
Dim BindingSource1 As New BindingSource
Dim BindingSource2 As New BindingSource

Dim DataTable1 As DataTable = GetDT1()
Dim DataTable2 As DataTable = GetDT2()

DataSet.Tables.Add(DataTable1)
DataSet.Tables.Add(DataTable2)

Dim Rel As DataRelation = New DataRelation("R", DataSet.Tables("DT1").Columns("C1"), DataSet.Tables("DT2").Columns("C1"), True)
DataSet.Relations.Add(Rel)

BindingSource1.DataSource = DataSet
BindingSource1.DataMember = "DT1"

BindingSource2.DataSource = BindingSource1
BindingSource2.DataMember = "R"