【C#】DataGridView セルのイベント発生順について

C#DGVセルイベント発生順の記事のサムネイル C#

動作確認環境

・Windows11Pro ver26H2
・VisualStudio2026 ver 18.12.1
・.Net10.0

DataGridView セルのイベント発生順について

DGVのセル関連イベントについて、発生順がいつもよく分からなくなってしまうので備忘録として。

検証内容

  1. 入力するセルをマウスでダブルクリック
  2. 文字を入力「あいうえお」
  3. Enter押下

この手順で操作していく。

検証結果

1回目マウスクリック後

CellMouseDown
CellLeave
CellValidating
CellValidated
CellStateChanged
CellStateChanged
CellEnter
CellClick
CellMouseClick
CellMouseUp

2回目マウスクリック後

CellMouseDown
CellDoubleClick
CellMouseDoubleClick
CellMouseUp

編集開始後

CellBeginEdit
EditingControlShowing

Enter押下(セル移動)後

CellLeave
CellValidating
CellParsing
CellValueChanged
CellValidated
CellEndEdit
CellStateChanged
CellStateChanged
CellEnter

CellのKeyPressについて

CellKeyPressイベントというものは無い。もしCell内で編集しているときにKeyPressを使いたい場合は、以下の実装が必要。

EditingControlShowingのイベント内でKeyPressイベントを追加

// 編集用テキストボックス
private DataGridViewTextBoxEditingControl? DGVTextBox = null;

private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    var DGV = (DataGridView)sender;

    //表示されているコントロールがDataGridViewTextBoxEditingControlか調べる
    if (e.Control is DataGridViewTextBoxEditingControl)
    {
        // 編集のために表示されているコントロールを取得
        DGVTextBox = (DataGridViewTextBoxEditingControl)e.Control;

        // KeyPressイベントハンドラを追加
        DGVTextBox.KeyPress += new KeyPressEventHandler(dataGridView_TextBox_KeyPress);
    }
}

CellEndEditのイベント内でKeyPressイベントを削除

private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    var DGVSender = (DataGridView)sender;

    // KeyPressイベントハンドラを削除
    if (DGVTextBox != null)
    {
        DGVTextBox.KeyPress -= new KeyPressEventHandler(dataGridView_TextBox_KeyPress);
        DGVTextBox = null;
    }
}

KeyPressイベントの実装

private void customDataGridView_TextBox_KeyPress(object? sender, KeyPressEventArgs e)
{ 
    ...(実装)...
}

KeyPress実装後の検証結果

上記のKeyPressイベントを実装した上でのイベントの発生順は以下の通り。

1回目マウスクリック後

CellMouseDown
CellLeave
CellValidating
CellValidated
CellStateChanged
CellStateChanged
CellEnter
CellClick
CellMouseClick
CellMouseUp

2回目マウスクリック後

CellMouseDown
CellDoubleClick
CellMouseDoubleClick
CellMouseUp

編集開始後

CellBeginEdit
EditingControlShowing

「あいうえお」変換確定(Enter押下)後

TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress
TextBox_KeyPress

※半角英数などの直接入力モードなら1文字入力ごとにKeyPressが走る

Enter押下(セル移動)後

CellLeave
CellValidating
CellParsing
CellValueChanged
CellValidated
CellEndEdit
CellStateChanged
CellStateChanged
CellEnter

コメント

タイトルとURLをコピーしました