Results 1 to 9 of 9

Thread: Prevent adding duplicate values in a datagridview

  1. #1

    Thread Starter
    Member
    Join Date
    May 2008
    Posts
    52

    Prevent adding duplicate values in a datagridview

    Hi guys, I have 2 datagridviews, the first is bound to a DB and the second is unbound.

    I use the below code to add the rows with a checkbox from DG1 to DG2, however I need to prevent it from adding duplicate entries, and preferably show a message telling you what the duplicate value is.

    Code:
      Dim c, t As Integer
            
            For t = 0 To DataGridView1.Columns.Count - 1
                DataGridView2.Columns.Add(DataGridView1.Columns(t).Clone())
            Next
    
            For c = 0 To DataGridView1.Rows.Count - 1
    
                If DataGridView1.Rows(c).Cells(3).Value = True Then
                    DataGridView2.Rows.Add(DataGridView1.Rows(c).Cells(0).Value, DataGridView1.Rows(c).Cells(1).Value)
                    DataGridView2.Columns(2).Visible = False
                    DataGridView2.Columns(3).Visible = False
                End If
                
            Next
    Any help would be appreciated.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,350

    Re: Prevent adding duplicate values in a datagridview

    Is every row in the second grid also in the first grid or might rows be removed from the first grid but still reside in the second? I ask because it may well be that the best option is to simply bind the second grid as well, to a filtered version of the data bound to the first grid. A more complete description of what the data represents would be useful.

  3. #3

    Thread Starter
    Member
    Join Date
    May 2008
    Posts
    52

    Re: Prevent adding duplicate values in a datagridview

    Hi, DG1 has 4 columns; name, surname, location and checkbox. DG2 only has 1 column; name.

    I mark checkboxes against the names I'm interested in and the above code copies only the first column (name) from DG1 to DG2. However, I want to prevent duplicate names from being added to DG2.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,350

    Re: Prevent adding duplicate values in a datagridview

    Quote Originally Posted by amaru96 View Post
    Hi, DG1 has 4 columns; name, surname, location and checkbox. DG2 only has 1 column; name.

    I mark checkboxes against the names I'm interested in and the above code copies only the first column (name) from DG1 to DG2. However, I want to prevent duplicate names from being added to DG2.
    So, is `name` actually given name or full name or something else? What happens if there are two people in the list with the same name?

  5. #5

    Thread Starter
    Member
    Join Date
    May 2008
    Posts
    52

    Re: Prevent adding duplicate values in a datagridview

    Name is their first name (ie. John, Mark...).

    Which list are you referring to? DG1 or DG2? I can add the same name multiple times - but this is what I want to prevent. Once I add the names to DG2, I then export them to CSV and do other things, but there can't be duplicate names in the list.

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,350

    Re: Prevent adding duplicate values in a datagridview

    Quote Originally Posted by amaru96 View Post
    Name is their first name (ie. John, Mark...).

    Which list are you referring to? DG1 or DG2? I can add the same name multiple times - but this is what I want to prevent. Once I add the names to DG2, I then export them to CSV and do other things, but there can't be duplicate names in the list.
    So what if John Smith and John Williams are both in grid 1 and you check them both? Do you only want to add John to grid 2 once?

  7. #7

    Thread Starter
    Member
    Join Date
    May 2008
    Posts
    52

    Re: Prevent adding duplicate values in a datagridview

    Yep, correct. A message stating that "John" already exists would be great.

  8. #8
    Hyperactive Member
    Join Date
    Sep 2014
    Posts
    404

    Re: Prevent adding duplicate values in a datagridview

    doubt this is the best way, but if you create a function which itterates through your existing names and returns true if the new name is added somthing like below

    Code:
    Public Function CheckDataDuplicate(DGV as Datagridview, Criteria as string, ColumnName as string) as Boolean
    
    CheckDataDuplicate= False
    
    For Each row as datagridviewrow in datagridview 
    If row.Column(ColumnName).ToString = Criteria then
    CheckDataDuplicate = True
    exit function
    End If
    Next
    
    end Function
    Please bare in mind this is a concept and was free written you may need to tweet the actual code to make it work

  9. #9
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,686

    Re: Prevent adding duplicate values in a datagridview

    Hello,

    If you are working with one column, name such as John then the following shows how to prevent duplicates. Button1 does this and shows a message what names where not added as they would have been duplicates while button2 just ignores duplicates and adds non-duplicates.

    Form code
    Code:
    Public Class Form1
        ''' <summary>
        ''' DataGridView columns created in the IDE
        ''' 1 CheckBox: ProcessColumn
        ''' 1 TextBox: FirstName
        ''' 
        ''' DataGridView2 columns created in the IDE
        ''' 1 TextBox: FirstNameClone
        ''' 
        ''' 2 buttons both do guard from duplicates
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks>
        ''' Requires language extension GetChecked in a code module
        ''' </remarks>
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Dim Names As New List(Of String) From
                {
                    "Mario",
                    "Carlos",
                    "Yoshi",
                    "Patricia",
                    "Helen",
                    "Philip",
                    "Daniel",
                    "Annette"
                }
    
            For Each FirstName As String In Names
                DataGridView1.Rows.Add(New Object() {False, FirstName})
            Next
    
            DataGridView1.AllowUserToAddRows = False
            DataGridView2.AllowUserToAddRows = False
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim CheckedRows As List(Of DataGridViewRow) = DataGridView1.GetChecked("ProcessColumn")
            If CheckedRows.Count > 0 Then
                Dim WouldBeDuplicates As New System.Text.StringBuilder
                For Each row As DataGridViewRow In CheckedRows
    
                    Dim TestIfExists =
                        (
                            From T In DataGridView2.Rows.Cast(Of DataGridViewRow)()
                            Where T.Cells("FirstNameClone").Value.ToString = row.Cells("FirstName").Value.ToString
                        ).FirstOrDefault
    
                    If TestIfExists Is Nothing Then
                        DataGridView2.Rows.Add(New Object() {row.Cells("FirstName").Value})
                    Else
                        WouldBeDuplicates.AppendLine(row.Cells("FirstName").Value.ToString)
                    End If
                Next
                If WouldBeDuplicates.ToString.Count > 0 Then
                    MessageBox.Show("The following were not added so not to create duplicates" &
                                    Environment.NewLine & WouldBeDuplicates.ToString)
                End If
            End If
    
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim CheckedRows As List(Of DataGridViewRow) = DataGridView1.GetChecked("ProcessColumn")
            If CheckedRows.Count > 0 Then
                Dim Test =
                    (
                        From T In CheckedRows
                        Select CStr(T.Cells("FirstName").Value)).ToArray.Except(
                            (
                                From T In DataGridView2.Rows.Cast(Of DataGridViewRow)()
                                Select CStr(T.Cells("FirstNameClone").Value)
                            ).ToArray
                    ).ToList
    
                If Test.Count > 0 Then
                    For Each item In Test
                        DataGridView2.Rows.Add(New Object() {item})
                    Next
                End If
            End If
        End Sub
    End Class
    The following is to be in a code module
    Code:
    <System.Diagnostics.DebuggerStepThrough()> _
    <Runtime.CompilerServices.Extension()> _
    Public Function GetChecked(ByVal GridView As DataGridView, ByVal ColumnName As String) As List(Of DataGridViewRow)
        Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() Where CBool(Rows.Cells(ColumnName).Value) = True).ToList
    End Function
    Name:  qqqqq.png
Views: 3191
Size:  28.7 KB

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width