Reputation: 35
I need to search for duplicate entries in a datagridview column (ex:itemcode) using vb.net ,and then I want to retrieve its row index so that I can combine those entries. My code below can only check for the duplicate if exists however I need to know the index.
Public Function Is_Duplicate_Grid(ByVal itemcode As long) As Boolean
For Each row As DataGridViewRow In Me.DataGridView1.Rows
If row.Cells("ItemCode").Value = itemcode Then
Return True
End If
Return False
Next
End Function
Upvotes: 1
Views: 5123
Reputation: 11
For i As Integer = 0 To Me.DataGridView1.RowCount - 1
For j As Integer = 0 To Me.DataGridView1.RowCount - 1
If i <> j Then
If DataGridView1.Rows(i).Cells("column_name").Value = DataGridView1.Rows(j).Cells("column_name").Value then
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.Red
end if
end if
next
next
Upvotes: 1
Reputation: 8004
I would look into Linq
which can be useful in this situation...
My Recommendation
Public Shared Function DuplicateGridIndex(ByVal _DataGridView As DataGridView, ByVal ColumnName As String, ByVal ItemCode As Long) As List(Of Integer)
Dim nList As New List(Of Integer)
Try
If _DataGridView IsNot Nothing AndAlso _DataGridView.Rows.Count > 0 AndAlso ColumnName IsNot Nothing AndAlso _DataGridView.Columns.Contains(ColumnName) Then
nList = _DataGridView.Rows.Cast(Of DataGridViewRow)().Where(Function(t) t.Cells(ColumnName).Value IsNot DBNull.Value AndAlso t.Cells(ColumnName).Value = ItemCode).Select(Function(r) r.Cells(ColumnName).RowIndex).ToList
End If
Catch ex As Exception
Return nList
End Try
Return nList
End Function
Explanation
DataGridView
, column we will search and the value to look for.cells.value
is not DBNull.Value
and finally where that cells value is equal to our search value passed into the function we are looking for. Short example usage
Dim Dups As New List(Of Integer)
Dups = DuplicateGridIndex(Me.DataGridView1, "ItemCode", 1432)
If Dups.Count > 0 Then
'Do what you need with each of the index's
End If
Your Original Modified (no error checking, nulls, column check etc...)
Public Function Is_Duplicate_Grid(ByVal itemcode As Long) As List(Of Integer)
Dim nList As New List(Of Integer)
For Each row As DataGridViewRow In Me.DataGridView1.Rows
If row.Cells("ItemCode").Value = itemcode Then
nList.Add(row.Index)
End If
Next
Return nList
End Function
Upvotes: 0