DataGridView – 在单击其他单元格时保持单元格选择

DataGridView – Maintain cells selection as other cells are clicked

当单元格被 selected 时,我正在改变它的颜色,但我需要当用户 clicks/select 一个单元格时它的颜色会改变,如果用户点击另一个单元格(在同一行),两者新单元格和前一个单元格得到 selected 并且两个单元格的颜色发生变化,并且如果用户再次单击第一个单元格然后它被取消 selected 并且只有第二个单元格是 select 已更改颜色。

这是我的代码:

 private void dataGridView1_CellClick(object sender,
   DataGridViewCellEventArgs e)
{
    List<DataGridViewRow> rowCollection = new List<DataGridViewRow>();



    foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
    {
        rowCollection.Add(dataGridView1.Rows[cell.RowIndex]);

    }




    foreach (DataGridViewRow row in rowCollection)
    {

            dataGridView1.Rows[row.Index].DefaultCellStyle.SelectionBackColor = Color.Pink;


    }

}

现在,当我 select 某个单元格时,它的颜色会发生变化,但是当我移动到其他单元格并 select 它时,之前 selected 的单元格会变色 selected 及其更改后的颜色恢复为默认颜色。

也许这会如你所愿..:[=​​13=]

private void DGV_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    DataGridViewCell cell = DGV[e.ColumnIndex, e.RowIndex];
    cell.Selected = !cell.Selected;
    cell.Style.BackColor = cell.Selected ? Color.Pink : Color.White;
}

但这实际上取决于您到底想要什么:如果您想添加到 SelectedCells 集合或从中删除,那么为单元格着色没有意义,因为它们始终具有 SelectionColor。如果您想维护自己的选定或彩色单元格集合,则需要将代码更改为如下内容:

List<DataGridViewCell> coloredCells = new List<DataGridViewCell>();

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{

    DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
    if (coloredCells.Contains(cell) ) coloredCells.Remove(cell);
    else coloredCells.Add(cell);
    cell.Style.BackColor = coloredCells.Contains(cell) ? Color.Pink : Color.White;
}

要删除蓝色选区,您可以使用:

private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
    dataGridView1.ClearSelection();
}

请注意,所有这些并不是用户所期望的,如果他们可以单击内容进行编辑,它可能会干扰..

//检查颜色,如果是粉色就把它变成白色。

foreach(rowCollection 中的 DataGridViewRow 行) { 如果(dataGridView1.Rows[row.Index].DefaultCellStyle.SelectionBackColor == Color.Pink) dataGridView1.Rows[row.Index].DefaultCellStyle.SelectionBackColor = Color.White; 别的 dataGridView1.Rows[row.Index].DefaultCellStyle.SelectionBackColor = Color.Pink; }