Compare datagridview1 and datagridview2 and mark same values c#

Total Post:159

Points:1117
C# 
C#
 15092  View(s)
Ratings:
Rate this:

I have a problem with comparing datagridviews. 

I need to compare 2 datagridviews and if values are same, mark them or do something. (I import values from excel)

I cant use linq it's slow.                                                                                                                                                                

I try this but it seems I cant get it to work:

for (int currentRow = 0; currentRow < grv.Rows.Count; currentRow++)
{
   var rowToCompare = grv.Rows[currentRow]; // Get row to compare against other rows
   // Iterate through all rows
   //
   foreach (var row in grv.Rows)
   { 
       if (rowToCompare.equals(row) continue; // If row is the same row being compared, skip.
       bool duplicateRow = true;
       // Compare the value of all cells
       //
       for (int cellIndex; cellIndex < row.Cells.Count; cellIndex++)
       {
          if (!rowToCompare.Cells[cellIndex].Value.equals(row.Cells[cellIndex].Value))
          {
             duplicateRow = false;
             break;
          }
       }
       if (duplicateRow)
       {
           grv.Rows.Remove(row);
       }
   }
}
  1. Post:412

    Points:2888
    Re: Compare datagridview1 and datagridview2 and mark same values c#

    Hi samuel,


    Try this :

    private void button1_Click(object sender, EventArgs e)
    {
        DataTable src1 = grv1.DataSource as DataTable;
        DataTable src2 = grv2.DataSource as DataTable;
        int index1 = 0;
        foreach (DataRow row1 in src1.Rows)
        {
            foreach (DataRow row2 in src2.Rows)
            {
                int index2 = 0;
                bool duplicateRow = true;
                for (int cellIndex = 0; cellIndex < row1.ItemArray.Count(); cellIndex++)
                {
                    if (!row1.ItemArray[cellIndex].ToString().Equals(row2.ItemArray[cellIndex].ToString()))
                    {
                        duplicateRow = false;
                        break;
                    }
                }
                if (duplicateRow)
                {
                    grv1.Rows[index1].DefaultCellStyle.BackColor = Color.Red;
                    grv2.Rows[index2].DefaultCellStyle.BackColor = Color.Red;
                }
                index2++;
            }
            index1++;
        }
    }

    This should color duplicates in red. Be sure that both gridview have the same cell number.


      Modified On Apr-04-2018 01:59:47 AM

Answer