1

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?

knart
  • 311
  • 2
  • 13

2 Answers2

2

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
tezzo
  • 10,858
  • 1
  • 25
  • 48
  • In `CellClick`, instead of setting `CurrentCell` to null It's better to first set `BackColor` to desired color and then set `SelectionBackColor` of cell to the same color as `BackColor`. Also in `SelectionChanged` set `SelectionBackColor` to `BackColor` of cell. – Reza Aghaei Nov 16 '16 at 10:56
  • 1
    answer updated with @RezaAghaei suggestions and KeyDown event which could be useful. – tezzo Nov 16 '16 at 14:18
0

What happens is, that when you click the cell, you call the cellformatting event. When you leave the cell you call it again. That's why it is updated after clicking on it. To force the CellFormattingEvent for all cells you can call the following:

DataGridView1.Invalidate()
Luke
  • 751
  • 2
  • 7
  • 32