DataGridViewCell的样式没有按时更新

时间:2016-11-16 10:25:05

标签: c# winforms datagridview datagridviewcellstyle

我正在编写一个C#应用程序(windows窗体),其中有一个代表迷宫的10x10 DataGridView。单击一个单元格时,我将相应的x和y添加到2D数组中。单击的每个单元格应显示黑色背景。

在CellClick上:

        int row = dataGridView1.CurrentCell.RowIndex;
        int column = dataGridView1.CurrentCell.ColumnIndex;

        maze[row, column] = 1;

        dataGridView1.Refresh();

我还为CellFormatting事件实现了一个处理程序:

if (maze[e.RowIndex,e.ColumnIndex] == 1){
       e.CellStyle.BackColor = Color.Black;
   }

现在,当我单击一个单元格时,样式未更新。当我在此之后单击另一个单元格时,将更新上一个单元格的样式。我已尝试同时控制Refresh()Update,但没有运气。

如何解决此问题,单击单元格样式会立即更新?

2 个答案:

答案 0 :(得分:1)

您可以使用这些事件在点击或按键时绘制当前单元格:

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

答案 1 :(得分:0)

当您单击单元格时,会调用cellformatting事件。当你离开牢房时,你再次呼叫它。这就是它点击后更新的原因。要强制所有单元格的CellFormattingEvent,您可以调用以下内容:

DataGridView1.Invalidate()