Reputation: 855
On my C# datagridview, I want the user to be acknowledged that they have indeed clicked on the cell.
I am using the datagridview's MouseDown and MouseUp events. The code functions correctly for the MouseDown event, by changing the cell color to Blue, but the MouseUp event does not change the color of the cell back to Transparent.
The resulting function is that all the cells I click on turn Blue, and stay Blue.
Am I not calling the Refresh method correctly? Is there a better way to achieve the same thing?
Here is my code:
private void Selector_dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Blue;
Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle;
Selector_dataGridView.Refresh();
}
private void Selector_dataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Transparent;
Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle;
Selector_dataGridView.Refresh();
}
Upvotes: 0
Views: 2433
Reputation: 12993
You need just a line in MouseDown
:
Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.Blue;
And revert back in MouseUp
:
Selector_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.White;
Upvotes: 1
Reputation: 3009
The cell mouse up handler will fire on whichever cell the mouse pointer is over at that time. I'm assuming you are moving you mouse away from the clicked cell after clicking. I would suggest clearing/refreshing all cells to transparent on mouseup but which will be a little overkill if you are dealing with a lot of cells.
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellmouseup(v=vs.110).aspx
Upvotes: 0
Reputation: 1808
In your Selector_dataGridView_CellMouseUp event, try changing the color to empty instead of transparent:
CellStyle.BackColor = Color.Empty;
Upvotes: 0