我有一个 dataGridView,我想在单击单元格时更改所选行的颜色。 我使用下面的代码执行此操作,但我的问题是当我选择第二行时,第一行没有更改回默认样式。
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
}
你能帮我吗?
您可以存储最后一个彩色单元格,并在激活另一个单元格时恢复其颜色。
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;
}
在您的方法中,您必须编写一个循环将所有单元格更新为默认颜色,然后将当前单元格更新为所需的颜色。