Combining Two DataTable in VB.Net:
In VB.NET or C# we can merge two DataTable using Table1.merge(Table2).Merging DataTable is an easy task. When wh megre two table then content of second table will append after content of first table.
If we want to combine content of two DataTable side by side ,this is not an easy task.
But if we want to combining two DataTable then add the following code:
Public Function CombineTable(_dtGridDetails As DataTable, _dtSubGridDetails As DataTable) As DataTable
'first create the datatable columns
Dim mydataSet As New DataSet()
mydataSet.Tables.Add(" ")
Dim myDataTable As DataTable = mydataSet.Tables(0)
'add left table columns
Dim dcLeftTableColumns As DataColumn() = New DataColumn(_dtGridDetails.Columns.Count - 1) {}
_dtGridDetails.Columns.CopyTo(dcLeftTableColumns, 0)
For Each LeftTableColumn As DataColumn In dcLeftTableColumns
If Not myDataTable.Columns.Contains(LeftTableColumn.ToString()) Then
myDataTable.Columns.Add(LeftTableColumn.ToString())
End If
Next
'now add right table columns
Dim dcRightTableColumns As DataColumn() = New DataColumn(_dtSubGridDetails.Columns.Count - 1) {}
_dtSubGridDetails.Columns.CopyTo(dcRightTableColumns, 0)
For Each RightTableColumn As DataColumn In dcRightTableColumns
If Not myDataTable.Columns.Contains(RightTableColumn.ToString()) Then
' if (RightTableColumn.ToString() != RightPrimaryColumn)
myDataTable.Columns.Add(RightTableColumn.ToString())
End If
Next
'add left-table data to mytable
For Each LeftTableDataRows As DataRow In _dtGridDetails.Rows
myDataTable.ImportRow(LeftTableDataRows)
Next
For nIndex As Integer = 0 To myDataTable.Rows.Count - 1
If nIndex = _dtSubGridDetails.Rows.Count Then
Exit For
End If
myDataTable.Rows(nIndex)(2) = _dtSubGridDetails.Rows(nIndex)(1)
Next
Return myDataTable
End Function
------------
Happy Coding.
No comments:
Post a Comment