Home > DeveloperSection > Forums > Compare datagridview1 and datagridview2 and mark same values c#
Samuel Fernandes
Samuel Fernandes

Total Post:154

Points:1082
Posted on    January-27-2014 3:01 AM

 C# C# 
Ratings:


 1 Reply(s)
 14159  View(s)
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);

       }

   }

}



Pravesh Singh

Total Post:411

Points:2881
Posted on    January-27-2014 3:19 AM

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.



Don't want to miss updates? Please click the below button!

Follow MindStick