bart-kn bart-kn - 8 months ago 45
C# Question

DataGridViewCell's style not updating on time

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;


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
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 put everything in CellClick event and set CurrentCell to Nothing:

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

    'set black background
    Me.DataGridView1.CurrentCell.Style.BackColor = Color.Black
    Me.DataGridView1.CurrentCell = Nothing

End Sub