0

迷路を表す 10x10 の DataGridView を持つ C# アプリケーション (Windows フォーム) を作成しています。セルをクリックすると、対応する 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コントロールを試みましたが、うまくいきませんでした。

この問題を解決するにはどうすればよいですか?セルのスタイルがクリックされるとすぐに更新されますか?

4

2 に答える 2

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
于 2016-11-16T10:38:16.307 に答える
0

何が起こるかというと、セルをクリックすると cellformatting イベントが呼び出されます。セルを離れると、もう一度呼び出します。そのため、クリックすると更新されます。すべてのセルに対して CellFormattingEvent を強制するには、次のように呼び出します。

DataGridView1.Invalidate()
于 2016-11-17T11:36:41.107 に答える