Jeff Brady
Jeff Brady

Reputation: 1498

Change color in datagridview based on differences in two datatables?

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 that are each bound to a datatable:

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

How can I compare each row, and highlight it in one (or both) of the datagridviews if they don't 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? Thank you!

EDIT: I tried this too, but it changes the color of every cell since it compares every row in dgvOldCM to a single 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;
        }
    }
}

Upvotes: 4

Views: 4639

Answers (3)

Garrett T.
Garrett T.

Reputation: 1

if (array1.SequenceEqual(array2))
{

}
else
{
//Do your action here!
}

Upvotes: -1

GuFigueiredo
GuFigueiredo

Reputation: 635

You can generate a Intersection of two Datatables, and then mark the rows:

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;
}

Upvotes: 2

Laszlo Boke
Laszlo Boke

Reputation: 1329

I would iterate on one of the gridview, comparing to the other like this:

    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;
            }
        }
    }

Upvotes: 4

Related Questions