Reputation:
I read in two files in two different datagridviews and I don't use any DataTable or DataSet. I need to compare both datagridviews/both files and need to mark the differences in the cells in a red color.
I already compare both files and show the differences in a message box, but it is not clear to notice them, so I wanted to show the differences in the datagridview by marking the cells red.
private void compareDatagridviews()
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
var row1 = dataGridView1.Rows[i].Cells;
var row2 = dataGridView2.Rows[i].Cells;
for (int j = 0; j < row1.Count; j++)
{
if (!row1[j].ToString().Equals(row2[j].ToString()))
{
dataGridView1.Rows[i].Cells[j].Style.BackColor = Color.Red;
dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Red;
}
}
}
}
Nothing happens when I press the button which calls the function above. Thanks in advance!
Upvotes: 0
Views: 1216
Reputation:
I solved the problem with this
private void compareDatagridviews()
{
DataTable src1 = GetDataTableFromDGV(dataGridView1);
DataTable src2 = GetDataTableFromDGV(dataGridView2);
for (int i = 0; i < src1.Rows.Count; i++)
{
var row1 = src1.Rows[i].ItemArray;
var row2 = src2.Rows[i].ItemArray;
for (int j = 0; j < row1.Length; j++)
{
if (!row1[j].ToString().Equals(row2[j].ToString()))
{
dataGridView1.Rows[i].Cells[j].Style.BackColor = Color.Red;
dataGridView2.Rows[i].Cells[j].Style.BackColor = Color.Red;
}
}
}
}
And this is the GetDataTableFromDGV function that I use:
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Visible)
{
// You could potentially name the column based on the DGV column name (beware of dupes)
// or assign a type based on the data type of the data bound to this DGV column.
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
Upvotes: 0
Reputation: 11
Your code is correct, but you have to specify that you want the value:
if (!row1[j].Value.ToString().Equals(row2[j].Value.ToString())) ...
Upvotes: 1