Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have two datagridview. dg1 has 3450 data while dg2 has 3250 data.if i click the btnFilter, the different data will show up to another datagridview. but now once i click the button, "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" has appeared in the line If "DataGridView1.Rows(x).Cells(1).Value.ToString = dgBranch.Rows(x).Cells(1).Value.ToString Then"

What I have tried:

i have tried this code but it returns the index out of range error

VB
Public Sub filter()
        Dim y As Integer = lblFilter.Text
        Form3.Label2.Text = Me.dgBranch.Rows(1).Cells(2).Value.ToString
        For x As Integer = DataGridView1.Rows.Count - 1 To 0 Step -1
            If DataGridView1.Rows(x).Cells(1).Value.ToString = dgBranch.Rows(x).Cells(1).Value.ToString Then
                If DataGridView1.Rows(x).Cells(y).Value.ToString <> dgBranch.Rows(x).Cells(y).Value.ToString Then
                    'MessageBox.Show(DataGridView1.Rows(x).Cells(1).Value.ToString + " " + dgBranch.Rows(x).Cells(1).Value.ToString + " " + DataGridView1.Rows(x).Cells(5).Value.ToString + " " + dgBranch.Rows(x).Cells(5).Value.ToString)
                    Form3.Show()
                    Form3.dgServer.Rows.Add(DataGridView1.Rows(x).Cells(0).Value, DataGridView1.Rows(x).Cells(1).Value.ToString, DataGridView1.Rows(x).Cells(3).Value.ToString, DataGridView1.Rows(x).Cells(4).Value.ToString, DataGridView1.Rows(x).Cells(5).Value.ToString)
                    Form3.dgBranch.Rows.Add(dgBranch.Rows(x).Cells(0).Value, dgBranch.Rows(x).Cells(1).Value.ToString, dgBranch.Rows(x).Cells(3).Value.ToString, dgBranch.Rows(x).Cells(4).Value.ToString, dgBranch.Rows(x).Cells(5).Value.ToString)
                End If
            Else
                MessageBox.Show("All Selected Items are the same!", "Filter", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Next
    End Sub<pre>
Posted
Updated 11-Jul-17 20:24pm
v2

1 solution

If the DGV's have different numbers of records then you cannot use the index of the larger DGV against the smaller.

dg1 can count backwards from 3450 rows, dg2 (dgbranch?) does not have a row number after 3249 therefore the index 3449 is out of range for that DGV.

In order to give a complete answer I would need to understand understand the relationship between the two DGV's and how you are pairing them but as a minimum you should test the index is in range of the second DGV before you use it or use the DGV with the lowest row count as the for loop control.
 
Share this answer
 
v3
Comments
Member 12374765 12-Jul-17 22:22pm    
Thank you Sir !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900