datagridview cell click event

≯℡__Kan透↙ 提交于 2019-12-03 03:21:14
Saurabh R S

You will also need to check the cell clicked is not the column header cell. Like this:

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());   
}

Check that CurrentCell.RowIndex isn't the header row index.

spajce
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());
}

The accepted solution throws an "object not set to an instance of an object" exception as null reference checking MUST happen before checking the actual value of a variable.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{    
    if (dataGridView1.CurrentCell == null ||
        dataGridView1.CurrentCell.Value == null ||
        e.RowIndex == -1) return;
    if (dataGridView1.CurrentCell.ColumnIndex.Equals(3))
        MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}

try this

        if(dataGridView1.Rows.Count > 0)
            if (dataGridView1.CurrentCell.ColumnIndex == 3)
                MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!