比较两个DataGridViews之间的单元格

时间:2014-03-06 14:47:24

标签: c#

美好的一天,

我想比较两个DataGridviews之间的单元格,并在源DataGridView(下面的GridView1)中标记不同的单元格。目前,我只能比较行。我是否可以通过相应的单元格比较DataGridViews单元格,并仅标记具有差异的单元格?

这是一个例子: 表格1: 3 6 8

表2: 2 6 5

private void button5_Click_1(object sender, EventArgs e)
{
    DataTable src1 = dataGridView1.DataSource as DataTable;
    DataTable src2 = dataGridView2.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].Equals(row2.ItemArray[cellIndex].ToString()))
                {
                    duplicateRow = true;
                    break;
                }
            }

            if (duplicateRow)
            {
                dataGridView1.Rows[index1].DefaultCellStyle.ForeColor = Color.Red; 
            }

            index2++;
        }
        index1++;
    }
}

非常感谢。

1 个答案:

答案 0 :(得分:2)

DataTable src1 = dataGridView1.DataSource as DataTable;
DataTable src2 = dataGridView2.DataSource as DataTable;

如果两个gridview具有相同数量的列和行:

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