2016-11-16 78 views
0

我寫一個C#應用程序(Windows窗體)中,我有一個10×10的DataGridView它代表一個迷宮。當點擊一個單元,I相應的x和y添加到2D陣列。每個被單擊的單元格應顯示一個黑色背景。的DataGridViewCell的風格不更新時間

在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的控制,但沒有運氣。

我怎樣才能解決這個問題,所以被點擊時單元格的樣式會立即更新?

回答

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 
+0

在'CellClick',而不是設置'CurrentCell'爲null,最好是先設置'BackColor'到所需的顏色,然後設置'的SelectionBackColor'單元格與「BackColor」顏色相同。此外,在'SelectionChanged'設置'SelectionBackColor'爲'細胞的BackColor'。 –

+1

答案與@RezaAghaei建議和KeyDown事件可能是有用的更新。 – tezzo

0

會發生什麼事是,當您單擊該單元格,可以調用cellformatting事件。當你離開細胞時,你可以再次調用它。這就是點擊它後更新的原因。要強制CellFormattingEvent所有單元您可以撥打以下:

DataGridView1.Invalidate()