DataGridViewCell 的样式没有及时更新
DataGridViewCell's style not updating on time
我正在编写一个 C# 应用程序(windows 表单),其中有一个代表迷宫的 10x10 DataGridView。单击单元格时,我将相应的 x 和 y 添加到二维数组中。单击的每个单元格应显示黑色背景。
在 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
控件,但没有成功。
如何解决这个问题,使单元格的样式在单击时立即更新?
您可以使用这些事件在单击或按下时绘制当前单元格:
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
发生的事情是,当您单击单元格时,您调用了单元格格式化事件。当您离开单元格时,您会再次调用它。这就是为什么它在单击后会更新。要为所有单元格强制执行 CellFormattingEvent,您可以调用以下命令:
DataGridView1.Invalidate()
我正在编写一个 C# 应用程序(windows 表单),其中有一个代表迷宫的 10x10 DataGridView。单击单元格时,我将相应的 x 和 y 添加到二维数组中。单击的每个单元格应显示黑色背景。
在 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
控件,但没有成功。
如何解决这个问题,使单元格的样式在单击时立即更新?
您可以使用这些事件在单击或按下时绘制当前单元格:
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
发生的事情是,当您单击单元格时,您调用了单元格格式化事件。当您离开单元格时,您会再次调用它。这就是为什么它在单击后会更新。要为所有单元格强制执行 CellFormattingEvent,您可以调用以下命令:
DataGridView1.Invalidate()