GridView 中的背景颜色

Background color in GridView

在我的 GridView 中,我有一个列名称 Switch,它可以在每一行中包含三个不同的值; L、B 和 T.

您可以根据值 L、B 和 T 关联不同的背景颜色吗?

例如,当列名称中包含行 Switch 值 L 时,背景色为黄色,当值 B 时,该行的背景色为绿色,值 T 时,该行的背景色是红色的。

你能帮帮我吗?

如果网格以 windows 形式存在,您可以这样做,

dataGridView1.Rows.OfType<DataGridViewRow>()
                  .Where(x => Convert.ToString(x.Cells["Switch"].Value) == "L").ToList()
                  .ForEach(x => x.DefaultCellStyle.BackColor = Color.Yellow);

希望这对您有所帮助...

您可以在 RowsAdded 活动中尝试这个

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        var row = dataGridView1.Rows[e.RowIndex];
        if (String.CompareOrdinal(row.Cells["Switch"].Value.ToString(), "L") == 0)
        {
            row.DefaultCellStyle.BackColor = Color.Yellow;
        }
        else if (String.CompareOrdinal(row.Cells["Switch"].Value.ToString(), "B") == 0)
        {
            row.DefaultCellStyle.BackColor = Color.Blue;
        }
    }