Prevent duplicate record Insert in DataGridView using C# and VB.Net in Windows Application

Last Reply 3 months ago By dharmendr

Posted 3 months ago

prevent adding duplicate data into datagridview 

Using this code I am getting the following result, it stops adding after the orange

Mango

Apple

Papay

Orange

Expected Output

Mango

Apple

Papay

Orange

Banana

Pineapple

Strawberry

Blueberry

Dim datatable As DataTable = New DataTable
datatable.Columns.Add("Items")
datatable.Rows.Add("Mango")
datatable.Rows.Add("Apple")
datatable.Rows.Add("Papaya")
datatable.Rows.Add("Orange")
datatable.Rows.Add("Banana")
datatable.Rows.Add("Pineapple")
datatable.Rows.Add("Strawberry")
datatable.Rows.Add("Blueberry")
Me.Combobox1.datasource = datatable

Dim Found As Boolean = False
If datatable IsNot Nothing AndAlso datatable.Rows.Count > 0 Then
    For i = 0 To datatable.Rows.Count - 1
        For j = 0 To Me.DataGridView2.Rows.Count - 1
            If Convert.ToString(Me.DataGridView2.Rows(j).Cells(1).Value) = Combobox1.SelectedItem Then ' Selected Item = Orange
                Found = True
                'Exit For
            End If
        Next
        If Not Found Then
            Me.DataGridView2.Rows.Add(datatable.Rows(i)(0).ToString())
        End If
    Next
End If

 

This question does not have replies that have been liked.