如何比较dataGridView中的2行并突出显示不同的单元格?

时间:2014-12-31 14:19:02

标签: c# datagridview

如何比较dataGridView中的两个选定行? 1.-我需要知道如何检测两个选定的行 2.-比较两个选定的行 3.-突出显示差异"细胞"

我试过这个,但不幸的是我迷路了......

DataTable src1 = dataGridView1.DataSource as DataTable; //THIS IS PROBABLY NOT NEEDED
    DataTable src2 = dataGridView1.DataSource as DataTable;
        int index1 = 0;

        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;
                    dataGridView1.Rows[i].Cells[j].Style.BackColor = Color.Red;
                }
            }
        }

1 个答案:

答案 0 :(得分:3)

实际上你的代码不好我会回答你的问题:

1.-我需要知道如何检测两个选定的行

dataGridView1.SelectedRows

2.-比较两个选定的行,它应该看起来类似于以下内容:

for (int i = 0; i < dataGridView1.SelectedRows.Count-1; i++)
{
    for (int j = 0; j < dataGridView1.SelectedRows.rows[i].Cells.Count; j++)
    {
        if(dataGridView1.SelectedRows.rows[i].Cells[j].value.Equals(dataGridView1.SelectedRows.rows[i+1].Cells[j].value))
        {
            dataGridView1.SelectedRows.Rows[i].Cells[j].Style.BackColor = Color.Red;
            dataGridView1.SelectedRows.Rows[i+1].Cells[j].Style.BackColor = Color.Red;
        }
    }    
}

3.-突出显示差异“细胞”

  dataGridView1.SelectedRows.Rows[i].Cells[j].Style.BackColor = Color.Red;
  dataGridView1.SelectedRows.Rows[i+1].Cells[j].Style.BackColor = Color.Red;