Change color in datagridview based on differences in two data types?

I have two datatables, each with 1 column:

dtTempCM dtOldTempCM 

In both tables, the only column name is Column1

I also have 2 datagridviews in the form, each of which is bound to a datatable:

 dgvCurrentCM.DataSource = dtTempCM; dgvOldCM.DataSource = dtOldTempCM; 

How can I compare each row and select it in one (or both) datagridviews objects if they do not match? So far I have this:

 foreach (DataRow row1 in dtTempCM.Rows) { foreach (DataRow row2 in dtOldTempCM.Rows) { var array1 = row1.ItemArray; var array2 = row2.ItemArray; if (array1.SequenceEqual(array2)) { //change row/cell color in dgvCurrentCM to red //change row/cell color in dgvOldCM to red } } } 

Any ideas? Thanks!

EDIT: I tried this too, but it changes the color of each cell as it compares each row in dgvOldCM with one row in dgvCurrentCM:

 foreach (DataGridViewRow row1 in dgvCurrentCM.Rows) { foreach (DataGridViewRow row2 in dgvOldCM.Rows) { if (row1.Cells[0].Value != row2.Cells[0].Value) { row1.DefaultCellStyle.ForeColor = Color.Red; row2.DefaultCellStyle.ForeColor = Color.Red; } } } 
+4
source share
3 answers

I would iterate over one of the gridview, compared to the other as follows:

  for (int i = 0; i < dgvCurrentCM.RowCount; i++) { if (dgvCurrentCM.Rows[i].Cells[0].Value != null) { if ((int)dgvCurrentCM.Rows[i].Cells[0].Value != (int)dgvOldCM.Rows[i].Cells[0].Value) { dgvCurrentCM.Rows[i].DefaultCellStyle.ForeColor = Color.Red; dgvOldCM.Rows[i].DefaultCellStyle.ForeColor = Color.Red; } } } 
+4
source

You can create the intersection of two datatables, and then mark the lines:

 DataTable dt1 = new DataTable(); DataTable dt2 = new DataTable(); dt1.Columns.Add("Col"); dt2.Columns.Add("Col"); for (int i = 0; i < 10; i++) { DataRow dr = dt1.NewRow(); dr["Col"] = i.ToString(); dt1.Rows.Add(dr); } for (int i = 5; i < 15; i++) { DataRow dr = dt2.NewRow(); dr["Col"] = i.ToString(); dt2.Rows.Add(dr); } var result = dt1.AsEnumerable().Intersect(dt2.AsEnumerable(), DataRowComparer.Default); dataGridView1.DataSource = dt1; dataGridView2.DataSource = dt2; for (int i = 0; i < dataGridView1.RowCount -1; i++) { DataRow currRow = ((DataRowView)dataGridView1.Rows[i].DataBoundItem).Row; if (result.Contains(currRow)) dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red; } 
+2
source
 if (array1.SequenceEqual(array2)) { } else { //Do your action here! } 
-1
source

All Articles