8

クリックされたセルのデータをメッセージ ボックスに表示するために、データグリッド ビューでセル クリックのイベントがあります。特定の列でのみ機能し、セルにデータがある場合にのみ機能するように設定しました

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.CurrentCell.ColumnIndex.Equals(3))
        if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)
            MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}

ただし、列ヘッダーのいずれかをクリックすると、空白のメッセージ ボックスが表示されます。理由がわかりません、何かヒントはありますか?

4

5 に答える 5

27

また、クリックしたセルが列ヘッダー セルではないことを確認する必要があります。このような:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.CurrentCell.ColumnIndex.Equals(3) && e.RowIndex != -1){
        if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)
            MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());   
}
于 2012-10-06T18:18:14.580 に答える
2
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{    
    if (e.RowIndex == -1) return; //check if row index is not selected
        if (dataGridView1.CurrentCell.ColumnIndex.Equals(3))
            if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)
                MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
于 2012-10-06T21:25:01.240 に答える
2

CurrentCell.RowIndexヘッダー行のインデックスではないことを確認してください。

于 2012-10-06T17:33:30.930 に答える