C# 为 DataGridView 中的 1 个单元格设置颜色

C# Set Color for 1 Cell in DataGridView

我正在寻找一种方法来通过单击为 1 个单元格设置特定的颜色。

我建了一个 Canteen Voter,你每天可以在 4 个菜单中选择。

我的 DataGridView 已连接到一个数据库,它从中接收所有信息,当您单击一个单元格时,它也会为登录用户存储在数据库中。

现在我希望能够在单击时单独为单元格着色。

到目前为止,我只找到了 SelectedCells 属性,但这实际上只为“SelectedCells”设置了颜色,当这些单元格再次失去焦点时它们又变白了。

我希望他们能够保留这种颜色,让用户更清楚他刚刚选择了哪道菜。

你应该设置 DataGridViewCell.Style 属性.

看看这个例子

private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0 || e.RowIndex == dataGridView1.NewRowIndex)
    {
        return;
    }
    var dataGridViewCellStyle = 
        new DataGridViewCellStyle(dataGridView1.DefaultCellStyle)
    {
        BackColor = Color.Gold
    };
    dataGridView1[e.ColumnIndex, e.RowIndex].Style = dataGridViewCellStyle;
}