行中只能更改一个单元格颜色
本文关键字:一个 单元格 颜色 | 更新日期: 2023-09-27 18:25:59
我现在使用win表单中的datagridview,当任何用户点击单元格时,我必须更改单元格的颜色,我必须将该单元格的颜色更改为红色,为此我使用了此代码
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Red;
dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle;
但现在,若用户选择了同一行中的任何其他单元格,则其颜色应更改为红色和先前选定的应使白色再次变为未选定。
您需要维护对以前选择的单元格的引用,以便将其更改回。
DataGridViewCell _currentCell = null; // class level variable
...
// inside your event, set the current cell back to white
if(_currentCell != null) _currentCell.Style.BackColor = Color.White;
// now set the current cell to the selected cell
_currentCell = dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex];
_currentCell.Style.BackColor = Color.Red;