如何在单独的列中比较两个单元格值并突出显示DataGridView中的差异

时间:2018-08-09 15:05:03

标签: c#

我一直在寻找这个问题,发现有人要求比较行值,但是我没有看到关于列值的询问,这正是我要尝试的事情。

我将在此dataGridView中获取的一些数据的示例如下所示

    2 2 2 2
    1 1 1 1
    1 2 1 1 
    2 2 2 1
    1 2 2 2

我希望将最后三行突出显示为具有差异,因为并非这些列中的所有数字都匹配。如果有办法突出显示不匹配的特定数字,那就更好了。

这将与比较行值的方法相同吗?如果没有,我该怎么做?

我提到的有关行比较问题的帖子可以在how to compare 2 rows in a dataGridView and highlight the different cells?

中找到

1 个答案:

答案 0 :(得分:1)

以下方法应突出显示每个,其中值不统一。

    public void HighlightNonUniformRows()
    {
        foreach (DataGridViewRow r in excelView_DGV.Rows)
        {
            r.DefaultCellStyle.BackColor = Color.White; // set to default until non-uniform value is detected
            for (int i = 0; i < r.Cells.Count - 1; i++)
            {
                int j = i + 1;
                if (!r.Cells[i].Value.Equals(r.Cells[j].Value))
                {
                    r.DefaultCellStyle.BackColor = Color.Red; // or other desired highlight color
                    break;
                }
            }
        }
    }

您还提到了“突出显示不匹配的特定数字”。假设给定行中的一个数字最多不同于其他数字(如您的示例数据),则可以使用下面的修改方法来完成。

    public void HighlightNonUniformRowCells()
    {
        foreach (DataGridViewRow r in excelView_DGV.Rows)
        {
            r.DefaultCellStyle.BackColor = Color.White; // set to default until non-uniform value is detected
            for (int i = 0; i < r.Cells.Count - 1; i++)
            {
                int j = i + 1;
                if (!r.Cells[i].Value.Equals(r.Cells[j].Value))
                {
                    if (i == 0 && r.Cells[j].Equals(r.Cells[j + 1])) r.Cells[i].Style.BackColor = Color.Red; // edge case - first cell contains the non-uniform value
                    else r.Cells[j].Style.BackColor = Color.Red;
                    break;
                }
            }
        }
    }