0
votes

Using C# WindowsForms,

I have 2 Datagridviews, each Datagridview has 2 columns.

I want to compare DT1 with DT2 rows, if DT1 (Col1 and Col2) is found in DT2 row (Col1 and Col2) then DT1 row and DT2 row will be removed/deleted.

Diagram of the explained above

Error Row index provided is out of range

Code Start Here
{
        bool MatchFound = false;

        List<int> IndexToRemoveFromGrid = new List<int>();


        //Loop Table 1 and get Row Values for Col1+Col2
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewRow T1Col1row = dataGridView1.Rows[row.Index];
            DataGridViewRow T1Col2row = dataGridView1.Rows[row.Index];
            string T1Col1RX = (string)T1Col1row.Cells[0].Value + (string)T1Col1row.Cells[1].Value;

            MatchFound = false;

            //Loop Table 2 and get Row Values for Col1+Col2
            foreach (DataGridViewRow rowT2 in dataGridView2.Rows)
            {
                DataGridViewRow T2Col1row = dataGridView2.Rows[rowT2.Index];
                DataGridViewRow T2Col2row = dataGridView2.Rows[rowT2.Index];
                string T2Col1RX = (string)T2Col1row.Cells[0].Value + (string)T2Col1row.Cells[1].Value;

                if (MatchFound == false)
                {
                    //Compare Table 1 RX to Table2 RX , If matched then deleted row on both sides
                    if (String.Compare(T1Col1RX, T2Col1RX, false) == 0)
                    {
                        if (row.Index > -1 && rowT2.Index > -1)
                        {
                            IndexToRemoveFromGrid.Add(row.Index);
                        }
                        MatchFound = true;
                    }
                }
            }
        }

        for (int i = 0; i <= IndexToRemoveFromGrid.Count(); i++)
        {
            dataGridView1.Rows.RemoveAt(i);
            dataGridView2.Rows.RemoveAt(i);
        }
    }
1
Datagridviews have collections of data, just compare contents and remove the unncessary from the containers.Gnqz
I wrote this however i am facing an issue with index value, return -1 and exceptionYazzan
What exception did you get and when it occured?Gnqz
I solved the exception, i had something wrong with the loop, however i fixed it. My issue now is that when i first run it removes rows and when i run again it will remove more rows even that they are not the same valueYazzan

1 Answers

0
votes

You should compare the data bounded to the DataGrid, that will be better than accessing the properties of the grid itself.