c#在数据网格视图中突出显示单元格,其中一个特定单元格重复,而其他任何单元格重复

时间:2018-07-03 10:25:57

标签: c# datagridview duplicates highlight

您好,我有一个datagridview,其中填充了数据,例如姓名,年龄和爱好。

现在,我希望字段年龄重复且名称或兴趣爱好都重复的字段突出显示,但字段必须重复年龄 高兴。

到目前为止,我已经找到了用于突出显示年龄相同的行并突出显示该行中的“年龄”列的代码:

var rows = dataGridView1.Rows.OfType<DataGridViewRow>()

var duplettes = rows.GroupBy(dgvrow => dgvrow.Cells["age"].Value.ToString())
            .Where(item => item.Count() > 1)
            .SelectMany(dgvrow => dgvrow.ToList());


    foreach (var row in duplettes)
{
            row.DefaultCellStyle.BackColor = Color.Yellow;
            row.Cells["age"].Style.ForeColor = Color.Red;
}

如果两个孩子的年龄相同,我希望通过更改前景色来突出显示他们的年龄,并且我希望通过更改背景色来突出显示他们所在的行。

如果两个孩子被称为鲍勃(或萨莉或其他名字,只要名字是相同的)并且他们的年龄是相同的,我希望通过改变前景色来突出他们的名字。

现在,如果两个孩子的名字都叫鲍勃(或萨莉或其他名字,名字都需要相同),并且他们两个都有重复的年龄,但是他们没有相同的年龄,我不希望他们的名字突出显示。

爱好也一样。

1 个答案:

答案 0 :(得分:1)

这是我的解决方案。我假设您要突出显示满足逻辑条件row1.age == row2.age => (row1.name == row2.name || row1.hobby == row2.hobby)的行。如果您寻求其他条件,请告诉我。

编辑:抱歉,我最初的答案设置了错误的黄色

编辑2:实际上应更改网格视图的更新版本

编辑3:使用其他方法更新行

编辑4:清除数据源,然后添加包含旧值的修改后的列表

public void HighlightRows()
{
    var rows = dataGridView1.Rows.OfType<DataGridViewRow>().ToList();

    DataGridViewRow row = new DataGridViewRow();

    MatchAllRows(rows);

    dataGridView1.DataSource = null;
    dataGridView1.Rows.Clear();
    dataGridView1.Rows.AddRange(rows.ToArray());
}

private void MatchAllRows(List<DataGridViewRow> rows)
{
    for (int i = 0; i < rows.Count() - 1; i++)
        for (int j = i + 1; j < rows.Count(); j++)
            if (rows[i].Cells["age"] == rows[j].Cells["age"])
                MatchTwoRows(rows[i], rows[j]);
}

private void MatchTwoRows(DataGridViewRow row1, DataGridViewRow row2)
{
    void Match(string key)
    {
        if (row1.Cells[key].Value == row2.Cells[key].Value)
        {
            row1.Cells[key].Style.ForeColor = Color.Red;
            row2.Cells[key].Style.ForeColor = Color.Red;

            row1.Cells[key].Style.BackColor = Color.Yellow;
            row2.Cells[key].Style.BackColor = Color.Yellow;
        }
    }

    List<string> keys = new List<string> { "name", "age", "hobby" };

    foreach (string key in keys)
        Match(key);
}
相关问题