I am writing a C# application (windows forms) in which I have a 10x10 DataGridView which represents a maze. When a cell is clicked, I add the corresponding x and y to a 2D array. Each cell that is clicked, should display a black background.
On CellClick:
int row = dataGridView1.CurrentCell.RowIndex;
int column = dataGridView1.CurrentCell.ColumnIndex;
maze[row, column] = 1;
dataGridView1.Refresh();
I've also implemented a handler for CellFormatting event:
if (maze[e.RowIndex,e.ColumnIndex] == 1){
e.CellStyle.BackColor = Color.Black;
}
Now when I click a cell, the style is not being updated. When I click another cell after that, the previous cell's style is updated. I've tried to both Refresh()
and Update
the control, but no luck.
How can I solve this problem, so a cell's style is immediately updated when it is clicked?
You can use these events to paint current cell on click or key down:
Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
'put here your code to add CurrentCell to maze array
Me.PaintCurrentCell()
End Sub
Private Sub DataGridView1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
If e.KeyCode = Keys.Space Then Me.PaintCurrentCell()
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.SelectionChanged
Me.DataGridView1.CurrentCell.Style.SelectionBackColor = Me.DataGridView1.CurrentCell.Style.BackColor
End Sub
Private Sub PaintCurrentCell()
Me.DataGridView1.CurrentCell.Style.BackColor = Color.Black
Me.DataGridView1.CurrentCell.Style.SelectionBackColor = Color.Black
End Sub