Results 1 to 20 of 20

Thread: How to prevent making duplicated rows in datagridview table

  1. #1

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    How to prevent making duplicated rows in datagridview table

    Hello,
    Any idea how to do that?

  2. #2
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: How to prevent making duplicated rows in datagridview table

    Bound or unbound? You need to FULLY explain what your trying to achieve .

  3. #3

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    Quote Originally Posted by wes4dbt View Post
    Bound or unbound? You need to FULLY explain what your trying to achieve .
    I used unbounded mode. I made columns and rows programmatically. When datagridview is populated I need to remove all duplicated rows. All rows need to be unique.

    I tried to make with this code:
    Code:
     'Dim i, j As Integer
    
            'For i = 0 To DataGridView1.Rows.Count - 1
            '    For j = 0 To DataGridView1.Rows.Count - 1
            '        If i.ToString = j.ToString Then
            '        Else
            '            DataGridView1.Rows.RemoveAt(j)
            '        End If
            '    Next
            'Next
    Thanks in advance.

  4. #4
    Fanatic Member louvelle's Avatar
    Join Date
    Jun 2008
    Posts
    513

    Re: How to prevent making duplicated rows in datagridview table

    You could use the SQL DISTINCT to remove duplicate values.

    Manny Pacquiao once posted in his twitter:
    It doesn't matter if the grammar is wrong, what matter is that you get the message

  5. #5
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: How to prevent making duplicated rows in datagridview table

    Quote Originally Posted by louvelle View Post
    You could use the SQL DISTINCT to remove duplicate values.
    That's true if the data is from a database. If that's the case, why is it unbound. The question that needs to be answered before we can help is, Where is the data that you use to populate the dgv coming from.

  6. #6
    Addicted Member
    Join Date
    Oct 2004
    Location
    Philippines
    Posts
    149

    Re: How to prevent making duplicated rows in datagridview table

    Why don't you just bind it and if there are duplicates check the object that you are binding to your grid, if there are really duplicates in it then check your query.

  7. #7

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    Quote Originally Posted by wes4dbt View Post
    That's true if the data is from a database. If that's the case, why is it unbound. The question that needs to be answered before we can help is, Where is the data that you use to populate the dgv coming from.
    The data that I use to populate dgv is in one text document which I opening using "open file dialog". So, everytime when I click on button "open" and shows path of .txt file(everytime is diferent one), and when file is loaded, dgv is populated automaticaly but with lot of duplicates. I need to remove all duplicates by first column and than dgv will show only unique data.

    That's all.
    Thanks

  8. #8
    Addicted Member
    Join Date
    Oct 2004
    Location
    Philippines
    Posts
    149

    Re: How to prevent making duplicated rows in datagridview table

    Can you post an example content of your textfile.

  9. #9

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    Quote Originally Posted by Zelot View Post
    Can you post an example content of your textfile.
    Textfile consist words separated by ",". For me it's not a problem to split all text by "," and import words into the datagridview. Problem is how to remove duplicates after that. Better solution for me is how to prevent importing of duplicates. Any of solution will be ok.

  10. #10
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: How to prevent making duplicated rows in datagridview table

    blueye89,

    You keep making us pry the necessary information from you bit by bit. Zelot, asked to see an example of the data but you didn't provide it. The amount of columns or the amount of rows or is it just one column that has to be checked for duplicates. All these things can effect how to solve this problem. Remember, we know absolutely nothing about your project. Seeing an example of the data and the code you use to load the dvg would be very helpful.

  11. #11

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    Quote Originally Posted by wes4dbt View Post
    blueye89,You keep making us pry the necessary information from you bit by bit. Zelot, asked to see an example of the data but you didn't provide it. The amount of columns or the amount of rows or is it just one column that has to be checked for duplicates. All these things can effect how to solve this problem. Remember, we know absolutely nothing about your project. Seeing an example of the data and the code you use to load the dvg would be very helpful.

    Hello wes4dbt,

    Name:  01.png
Views: 5869
Size:  9.3 KB
    Here is a code.

    Code:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim Name As New DataGridViewTextBoxColumn
            Name.Name = "Name"
            Name.HeaderText = "Name"
            Name.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            Name.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            Name.Width = 200
            Name.SortMode = 0
            DataGridView1.Columns.Add(Name)
    
        End Sub
    
        Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
            'Open TXT
            Dim openFileDialog1 As New OpenFileDialog
    
            openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            openFileDialog1.Title = "Text Documents"
            openFileDialog1.Filter = "Text Documents (*.txt)|*.txt"
            openFileDialog1.FilterIndex = 1
            openFileDialog1.RestoreDirectory = True
    
            If openFileDialog1.ShowDialog() = DialogResult.OK Then
                'Clear DGW
                DataGridView1.Rows.Clear()
    
                Dim stFilePathAndName As String = openFileDialog1.FileName
                TextBox1.Text = stFilePathAndName
                Dim sr As IO.StreamReader = New IO.StreamReader(stFilePathAndName)
                Dim line As String
                Do While Not sr.EndOfStream
                    line = sr.ReadLine()
                    Dim aryTextFile() As String
                    aryTextFile = line.Split(",")
                    For i = 0 To UBound(aryTextFile)
                        DataGridView1.Rows.Add(aryTextFile(i))
                    Next i
                    If line = Nothing Then Continue Do ' This line skips blanks
                Loop
                sr.Close()
            Else
                openFileDialog1.Dispose()
            End If
        End Sub
        
        Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
            Me.Close()
        End Sub

  12. #12

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    I have solution which removes only one duplicate by single click on button.
    I need to remove it all.

    Code:
        For intI As Integer = 0 To DataGridView1.Rows.Count - 1
                For intJ As Integer = intI + 1 To DataGridView1.Rows.Count - 1
                    If DataGridView1.Rows(intI).Cells(0).Value = DataGridView1.Rows(intJ).Cells(0).Value Then
                        DataGridView1.Rows.RemoveAt(intI)
                        Exit Sub
                    End If
                Next
            Next

  13. #13
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,206

    Re: How to prevent making duplicated rows in datagridview table

    Is there some reason you don't remove the duplicates before you load the dgv. Anyway, an Array has a method named "Distinct". This will remove all duplicates.
    Code:
    Dim arrDistinct() as String = aryTextFile.Distinct.ToArray
    Then clear the dgv and reload using arrDistinct.

  14. #14
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    Re: How to prevent making duplicated rows in datagridview table

    Quote Originally Posted by blueye89 View Post
    Textfile consist words separated by ",". For me it's not a problem to split all text by "," and import words into the datagridview. Problem is how to remove duplicates after that. Better solution for me is how to prevent importing of duplicates. Any of solution will be ok.
    Here is an example based on a DataGridView that has two columns (Name and Age); however the number of columns is not relevant. It creates some data and then loops through that data adding only unique rows to the DataGridView.

    Read about the DataGridViewRow.CreateCells Method . In the example code, I add the data as an Object array, but the "values" parameter is defined as a ParamArray that will allow you list each value separately. i.e.
    Code:
    r.CreateCells(dgv1, "Mary", 22)
    VB.Net Code:
    1. Private Sub Test()
    2.    ' simulated data
    3.    Dim dataSource As New List(Of Object()) '= { {"Joe", 24}, {"Joe", 26}, {"Joe", 28}}
    4.    With dataSource
    5.       .Add(New Object() {"Joe", 24})
    6.       .Add(New Object() {"Joe", 26})
    7.       .Add(New Object() {"Joe", 24})
    8.       .Add(New Object() {"Bill", 24})
    9.       .Add(New Object() {"Joe", 24})
    10.    End With
    11.  
    12.    'Simulate reading data
    13.    Dim r As DataGridViewRow
    14.    For Each datagroup As Object() In dataSource
    15.       r = New DataGridViewRow
    16.       r.CreateCells(dgv1, datagroup) ' creates the cells per dgv1 row template and adds values
    17.       If Not RowExists(dgv1, r) Then dgv1.Rows.Add(r) ' add only if row is unique
    18.    Next
    19. End Sub
    20.  
    21. Private Function RowExists(ByVal dgv As DataGridView, ByVal r As DataGridViewRow) As Boolean
    22.    Dim ret As Boolean
    23.    For Each row As DataGridViewRow In dgv.Rows
    24.       If row.IsNewRow Then Continue For
    25.       ret = DgvRowValuesEqual(row, r)
    26.       If ret Then Exit For
    27.    Next
    28.    Return ret
    29. End Function
    30.  
    31. Private Function DgvRowValuesEqual(ByVal r1 As DataGridViewRow, ByVal r2 As DataGridViewRow) As Boolean
    32.    Dim ret As Boolean = (r1.Cells.Count = r2.Cells.Count)
    33.    If ret Then
    34.       For i As Int32 = 0 To r1.Cells.Count - 1
    35.          Dim bothNull As Boolean = (r1.Cells(i).Value Is Nothing) And (r2.Cells(i).Value Is Nothing)
    36.          If Not bothNull Then
    37.             If (r1.Cells(i).Value Is Nothing) OrElse (r2.Cells(i).Value Is Nothing) Then
    38.                ret = False
    39.                Exit For
    40.             ElseIf r1.Cells(i).Value.GetType IsNot r2.Cells(i).Value.GetType Then
    41.                Throw New Exception(String.Format("Cell value types are different. r1 is {0} and r2 is {1}.", r1.Cells(i).Value.GetType.Name, r2.Cells(i).Value.GetType.Name))
    42.             ElseIf Comparer.Default.Compare(r1.Cells(i).Value, r2.Cells(i).Value) <> 0 Then
    43.                ret = False
    44.                Exit For
    45.             End If
    46.          End If 'bothNull
    47.       Next
    48.    End If
    49.  
    50.    Return ret
    51. End Function

  15. #15
    Lively Member elielCT's Avatar
    Join Date
    Jun 2011
    Posts
    89

    Re: How to prevent making duplicated rows in datagridview table

    would this work?


    VB.NET Code:
    1. Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
    2.         'Open TXT
    3.         Dim openFileDialog1 As New OpenFileDialog
    4.  
    5.         openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    6.         openFileDialog1.Title = "Text Documents"
    7.         openFileDialog1.Filter = "Text Documents (*.txt)|*.txt"
    8.         openFileDialog1.FilterIndex = 1
    9.         openFileDialog1.RestoreDirectory = True
    10.  
    11.         If openFileDialog1.ShowDialog() = DialogResult.OK Then
    12.             'Clear DGW
    13.             DataGridView1.Rows.Clear()
    14.  
    15.             Dim stFilePathAndName As String = openFileDialog1.FileName
    16.             TextBox1.Text = stFilePathAndName
    17.             Dim sr As IO.StreamReader = New IO.StreamReader(stFilePathAndName)
    18.             Dim line As String
    19.             Do While Not sr.EndOfStream
    20.                 line = sr.ReadLine()
    21.                 Dim aryTextFile() As String
    22.                 aryTextFile = line.Split(CChar(","))
    23.                 For i = 0 To UBound(aryTextFile)
    24.                     Dim dataRow As New DataGridViewRow
    25.                     dataRow.Cells(0).Value = aryTextFile(i)
    26.  
    27.                     If DataGridView1.Rows.Contains(dataRow) Then Continue For
    28.                     DataGridView1.Rows.Add(dataRow)
    29.                 Next i
    30.                 If line = Nothing Then Continue Do ' This line skips blanks
    31.             Loop
    32.             sr.Close()
    33.         Else
    34.             openFileDialog1.Dispose()
    35.         End If
    36.     End Sub
    Last edited by elielCT; Sep 1st, 2014 at 10:49 PM.

  16. #16

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    Quote Originally Posted by elielCT View Post
    would this work?


    VB.NET Code:
    1. Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
    2.         'Open TXT
    3.         Dim openFileDialog1 As New OpenFileDialog
    4.  
    5.         openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    6.         openFileDialog1.Title = "Text Documents"
    7.         openFileDialog1.Filter = "Text Documents (*.txt)|*.txt"
    8.         openFileDialog1.FilterIndex = 1
    9.         openFileDialog1.RestoreDirectory = True
    10.  
    11.         If openFileDialog1.ShowDialog() = DialogResult.OK Then
    12.             'Clear DGW
    13.             DataGridView1.Rows.Clear()
    14.  
    15.             Dim stFilePathAndName As String = openFileDialog1.FileName
    16.             TextBox1.Text = stFilePathAndName
    17.             Dim sr As IO.StreamReader = New IO.StreamReader(stFilePathAndName)
    18.             Dim line As String
    19.             Do While Not sr.EndOfStream
    20.                 line = sr.ReadLine()
    21.                 Dim aryTextFile() As String
    22.                 aryTextFile = line.Split(CChar(","))
    23.                 For i = 0 To UBound(aryTextFile)
    24.                     Dim dataRow As New DataGridViewRow
    25.                     dataRow.Cells(0).Value = aryTextFile(i)
    26.  
    27.                     If DataGridView1.Rows.Contains(dataRow) Then Continue For
    28.                     DataGridView1.Rows.Add(dataRow)
    29.                 Next i
    30.                 If line = Nothing Then Continue Do ' This line skips blanks
    31.             Loop
    32.             sr.Close()
    33.         Else
    34.             openFileDialog1.Dispose()
    35.         End If
    36.     End Sub
    It's not working.
    Code:
    dataRow.Cells(0).Value = aryTextFile(i)

  17. #17

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    Solution:
    Code:
       For intI As Integer = DataGridView1.Rows.Count - 1 To 0 Step -1
                For intJ As Integer = DataGridView1.Rows.Count - 1 To intI + 1 Step -1
                    If DataGridView1.Rows(intI).Cells(0).Value = DataGridView1.Rows(intJ).Cells(0).Value Then
                        DataGridView1.Rows.RemoveAt(intJ)
                    End If
                Next intJ
            Next intI

  18. #18
    Lively Member elielCT's Avatar
    Join Date
    Jun 2011
    Posts
    89

    Re: How to prevent making duplicated rows in datagridview table

    sorry i shouldve mentioned it wasnt tested, it was just to give you an idea..

    after trying to modify it, i couldnt get it to work correctly.. seems when you compare rows even if they have the same exact values it returns false.. almost as if it was comparing the instance.. even though there is an implicit method to check for instance equality.. so i turned to linq.. after some tries i couldnt get it so i did a little search as found this: http://stackoverflow.com/a/3322497.. so now the code looks like this and it works to prevent duplicates:


    VB.NET Code:
    1. Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
    2.         'Open TXT
    3.         Dim openFileDialog1 As New OpenFileDialog
    4.  
    5.         openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    6.         openFileDialog1.Title = "Text Documents"
    7.         openFileDialog1.Filter = "Text Documents (*.txt)|*.txt"
    8.         openFileDialog1.FilterIndex = 1
    9.         openFileDialog1.RestoreDirectory = True
    10.  
    11.         If openFileDialog1.ShowDialog() = DialogResult.OK Then
    12.             'Clear DGW
    13.             DataGridView1.Rows.Clear()
    14.  
    15.             Dim stFilePathAndName As String = openFileDialog1.FileName
    16.             TextBox1.Text = stFilePathAndName
    17.             Dim sr As IO.StreamReader = New IO.StreamReader(stFilePathAndName)
    18.             Dim line As String
    19.             Do While Not sr.EndOfStream
    20.                 line = sr.ReadLine()
    21.                 Dim aryTextFile() As String
    22.                 aryTextFile = line.Split(CChar(","))
    23.                 For i = 0 To UBound(aryTextFile)
    24.                     'to hold value used in iteration
    25.                     Dim lineNum = i
    26.                     'to hold duplicate entry, so we can test for it
    27.                     Dim duplicateEntry As IEnumerable(Of Object)
    28.  
    29.                     If Me.DataGridView1.RowCount > 0 Then
    30.                         duplicateEntry = From theRow In DataGridView1.Rows, _
    31.                    theCell In CType(theRow, DataGridViewRow).Cells _
    32.               Where CType(theCell, DataGridViewCell).Value.ToString = aryTextFile(lineNum) _
    33.               Select theCell
    34.  
    35.                         If duplicateEntry.Count > 0 Then
    36.                             Continue For
    37.                         End If
    38.  
    39.                     End If
    40.  
    41.                     DataGridView1.Rows.Add(aryTextFile(i))
    42.                 Next (i)
    43.                 If line = Nothing Then Continue Do ' This line skips blanks
    44.             Loop
    45.             sr.Close()
    46.         Else
    47.             openFileDialog1.Dispose()
    48.         End If
    49.     End Sub

  19. #19
    Addicted Member
    Join Date
    Oct 2004
    Location
    Philippines
    Posts
    149

    Re: How to prevent making duplicated rows in datagridview table

    Another variation of what @wes4dbt is suggesting. Load your content into an object then use distinct and then bind it to your grid. This will simplify what you are doing.

    C#.net Code:
    1. var contents = new List<String>();
    2. // file read goes here
    3. var data = contents.Distinct().Select(c => new { Name = c }).ToList();
    4. dgv.DataSource = data;

  20. #20

    Thread Starter
    Member
    Join Date
    Feb 2012
    Posts
    49

    Re: How to prevent making duplicated rows in datagridview table

    Thanks to all, I appreciate you helping me.

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