TheConfusedCoder
TheConfusedCoder

Reputation: 77

How to compare two cell values in separate columns and highlight the difference in a DataGridView

I was looking up this question and saw it was asked for comparing row values but I didn't see one asking about column values which is what I'm trying to do.

An example of some data i would be getting in this dataGridView would be something like this below

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

And I would want the last three rows to be highlighted as having differences because not all numbers in those columns match. If there's a way to highlight the specific number that doesn't match that's even better.

Would this be done the same way as comparing row values? If not how could I do this task?

The post I mentioned about the row comparison question can be found at how to compare 2 rows in a dataGridView and highlight the different cells?

Upvotes: 0

Views: 1523

Answers (1)

user8061994
user8061994

Reputation:

The below method should highlight each row where values are not uniform.

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

You also mentioned "highlighting the specific number that does not match". Assuming that a maximum of one number is different from the others in a given row (as in your example data), this can be done using the modified method below.

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

Upvotes: 1

Related Questions