1

实际问题似乎比标题所说的要复杂..但希望有人能弄清楚..

我有两个数据表,我打算将它们绑定到 Gridview。但我需要第一个 dt 的一点点和第二个 dt 的一点点。

第二个表只有一行表示第一个表中同一列中的每一行。

但是,两个表之间没有主键或关系。

希望我的解释足够清楚......非常感谢......期待很快有一个解决方案,。

例如,

在此处输入图像描述

我试过 datatable.merge 虽然。没有产生我想要的最后一张桌子。

4

2 回答 2

0

试试这个链接

http://social.msdn.microsoft.com/Forums/da-DK/adodotnetdataset/thread/ecb6a83d-b9b0-4e64-8107-1ca8757fe58c

要么使用 linq,要么将所有表放在数据集中,在数据表上创建 pk/fk 并以这种方式加入它们。

于 2012-05-28T15:06:35.823 回答
0
  ''' <summary>
  ''' Merge two datatables that have a 1:1 relationship
  ''' </summary>
  ''' <param name="dtb1">Required Datatable.</param>
  ''' <param name="dtb2">Required Datatable.</param>
  ''' <param name="dtb1MatchField">Required String. Field name in dtb1 to use to match records</param>
  ''' <param name="dtb2MatchField">Required String. Field name in dtb2 to use to match records</param>
  ''' <remarks></remarks>
  Private Function MergeDataTables(ByVal dtb1 As DataTable, ByVal dtb2 As DataTable, ByVal dtb1MatchField As String, ByVal dtb2MatchField As String) As DataTable
    Dim dtbOutput As DataTable = dtb1.Copy
    Dim lstSkipFields As New List(Of String)
    For Each dcl As DataColumn In dtb2.Columns
      Try
        dtbOutput.Columns.Add(dcl.ColumnName, dcl.DataType)
      Catch ex As DuplicateNameException
        lstSkipFields.Add(dcl.ColumnName)
      End Try
    Next dcl
    'Merge dtb2 records that match existing records in dtb1
    Dim dtb2Temp As DataTable = dtb2.Copy
    For int2 As Integer = dtb2Temp.Rows.Count - 1 To 0 Step -1
      Dim drw2 As DataRow = dtb2Temp.Rows(int2)
      Dim o2 As Object = drw2(dtb2MatchField)
      For Each drw1 As DataRow In dtbOutput.Rows
        Dim o1 As Object = drw1(dtb1MatchField)
        If o1.ToString = o2.ToString Then
          For Each dcl As DataColumn In dtb2Temp.Columns
            If Not lstSkipFields.Contains(dcl.ColumnName) Then
              drw1(dcl.ColumnName) = drw2(dcl.ColumnName)
            End If
          Next dcl
          dtb2Temp.Rows.Remove(drw2)
        End If
      Next drw1
    Next int2
    'add rows that weren't in dtb1
    For Each drw2 As DataRow In dtb2Temp.Rows
      Dim drw1 As DataRow = dtbOutput.NewRow
      For Each dcl As DataColumn In dtb2Temp.Columns
        drw1(dcl.ColumnName) = drw2(dcl.ColumnName)
      Next dcl
      dtbOutput.Rows.Add(drw1)
    Next drw2
    Return dtbOutput
  End Function
于 2012-05-29T04:56:01.510 回答