Comparison of data tables based on Specific Column

Posted by VIJI Saturday, July 4, 2009

The following VB.NET describes how to compare two data tables.

/*It accepts two Data Tables as Parameters and Search Column Index*/

/* It returns the rows found in both the tables and */

/* and rows found in First Table only */

Drag and drop Four GridViews

Name them as dbGridView1, dbGridView2, GridViewRowsInFirst, GridViewRowsInBoth

Populate the dbGridView1 with Some Value.

Populate the dbGridView2 With Some Value.


Call CompareDataTables(dbGridView1.DataSource, dbGridView2.DataSource, 0)




Private Sub CompareDataTables(ByVal dTable1 As DataTable, ByVal dTable2 As DataTable, ByVal SearchColIndex As Integer)

Dim dr As DataRow

Dim dtRowsInBoth = New DataTable() 'For Rows In Both

Dim dtRowsOnlyInFirst = New DataTable() 'For Rows In First Table

Dim MatchRow As DataRow

For Each dr in dTable1.Rows

MatchRow = dTable2.Rows.Find(dr.Item(SearchColIndex))

If MatchRow Is Nothing Then 'If the record is not in Table 2

dtRowsOnlyInFirst.Rows.Add(dr) 'Add to RowsInFirstTable

Else

dtRowsInBoth.Rows.Add (MatchRow) 'Add to RowsInBoth Table

End If

Next

dtRowsOnlyInFirst.AcceptChanges()

dtRowsInBoth.AcceptChanges()


'Now Populate the GridView With the data tables

populateRowsInFirstTableGrid(dtRowsOnlyInFirst)
populateRowsInBothTableGrid(dtRowsInBoth)




End Sub

Private Sub populateRowsInFirstTableGrid(ByVal dt As DataTable)
'Bind GridView
GridViewRowsInFirst.DataSource = dt
GridViewRowsInFirst.Refresh

End Sub


Private Sub populateRowsInBothTableGrid(ByVal dt As DataTable)
'Bind GridView
GridViewRowsInBoth.DataSource = dt
GridViewRowsInBoth.Refresh


End Sub

0 Responses to Comparison of data tables based on Specific Column

Post a Comment