如何在master-detail关系中使用“DataTable.Select(?)”

时间:2011-06-23 08:23:45

标签: c# vb.net datatable relationship master-detail

DataTable with Master Detail relationship in Dataset:

**product** 
--------------
product_id      (pK)
product_name       
product_price

**operator**
--------------
operator_id     (pK)   
operator_name

**machine**
--------------
machine_id      (pK)
product_id      (fK)
operator_id     (fK)


Contents of the DataTable is

**product** 
--------------
1   bag       20
2   shoe      15
3   clothes   30

**operator**
--------------
1   alex
2   bery

**machine**
--------------
1   1    1
2   2    2

我想使用DataTable.Select(???)如何显示如下数据?感谢。

**machine**
--------------
1    bag    alex
2    shoe   bery

这个程序正在运行,只有结果输出是(1 1 1),我想要这样的输出 (1包alex)

Dim dtTable As DataTable = MyDataset.Tables("machine")
Dim rowSearching() As DataRow

Try

   ' Problem in here... "dtTable.Select"
   rowSearching = dtTable.Select("Parent(fk_machine_product_id).product_id = product_id AND Parent(fk_machine_totalizer_id).totalizer_id = totalizer_id AND Parent(fk_machine_operator_id).operator_id = operator_id")

   If rowSearching.Length > 0 Then
      For Each dr As DataRow In rowSearching
        MessageBox.Show(CStr(dr.Item(0)) & " " & CStr(dr.Item(1)) & " " & CStr(dr.Item(2)))
      Next
   End If

Catch ex As Exception
   MessageBox.Show(ex.Message)
End Try


Thanks & Best Regard,
Dewi

1 个答案:

答案 0 :(得分:0)

@magnus,我找到了一个基于你的参考的解决方案,谢谢。

我不使用“DataTable.Select(?)”而是使用“GetParentRow”。详情如下,我将分享可能对其他人有用。感谢。

Dim childMachineDataTable As DataTable = MyDataset.Tables("machine")

Dim parentProductRow As DataRow = Nothing
Dim parentOperatorRow As DataRow = Nothing

Dim productName As New ArrayList
productName.Clear()

Dim operatorName As New ArrayList
operatorName.Clear()

For Each childRow As DataRow In childMachineDataTable.Rows
    parentProductRow = childRow.GetParentRow("fk_machine_product_id")
    parentOperatorRow = childRow.GetParentRow("fk_machine_operator_id")

    productName.Add(parentProductRow.Item(1))
    operatorName.Add(parentOperatorRow.Item(1))
Next

MessageBox.Show(CStr(productName.Item(0))  ' output: bag
MessageBox.Show(CStr(productName.Item(1))  ' output: shoe

MessageBox.Show(CStr(operatorName.Item(0)) ' output: alex
MessageBox.Show(CStr(operatorName.Item(1)) ' output: bary