繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM