C# - 选择单元格时更改行颜色

问题描述 投票:0回答:2

我有一个 dataGridView,我想在单击单元格时更改所选行的颜色。 我使用下面的代码执行此操作,但我的问题是当我选择第二行时,第一行没有更改回默认样式。

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
  dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
  dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
}

你能帮我吗?

c# datagridview
2个回答
0
投票

您可以存储最后一个彩色单元格,并在激活另一个单元格时恢复其颜色。

private System.Windows.Forms.DataGridViewRow lastColoredRow = null;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if(lastColoredRow!=null) {
        // Restore the coloring as needed
        lastColoredRow.DefaultCellStyle.BackColor = Color.White;
        lastColoredRow.DefaultCellStyle.ForeColor = Color.Black;
    }
    dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
    dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
    lastColoredRow = dataGridView1.CurrentRow;
}

0
投票

在您的方法中,您必须编写一个循环将所有单元格更新为默认颜色,然后将当前单元格更新为所需的颜色。

© www.soinside.com 2019 - 2024. All rights reserved.