0
votes

When cell is selected I am changing its color, but I need that when user clicks/select a cell it color get change and if user clicks another cell (in same row), both the new cell and the previous cell gets selected and color changes of both cells, AND if user click the first cell again then it gets de-selected and only the second cell is selected with changed color.

Here is my code:

 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;


    }

}

Right now when I select some cell it color changes but when I move to some other cell and select it, then previously selected cell gets deselected and its changed color revert back to default color.

2
Maybe you should educate your users about the use of the Control key? - TaW

2 Answers

0
votes

Maybe this will do what you want..:

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

But it really depends what exactly you want: If you want to add to and remove from the SelectedCells collection, then coloring the cells doesn't make sense, since these will always have the SelectionColor. If you want to maintain your own collection of selected or rather of colored Cells you would need to change the code to something like this:

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

To remove the blue selection you can use this:

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

Note that all this is not exactly what users will expect and if they can click on the content to edit it, it may well interfere..

0
votes

//check the color if it pink change it white.

foreach (DataGridViewRow row in rowCollection) { if(dataGridView1.Rows[row.Index].DefaultCellStyle.SelectionBackColor == Color.Pink) dataGridView1.Rows[row.Index].DefaultCellStyle.SelectionBackColor = Color.White; else dataGridView1.Rows[row.Index].DefaultCellStyle.SelectionBackColor = Color.Pink; }