DataGridView单元格点击事件

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

然而,每当我点击任何列标题时,一个空白消息框会出现。我无法弄清原因,有什么提示吗?
6个回答

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

请注意,在第一个条件之前应检查 dataGridView1.CurrentCell != null - MatanKri

2

请检查CurrentCell.RowIndex是否为标题行索引。


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

1
已接受的解决方案会抛出“对象未设置为对象实例”的异常,因为必须在检查变量的实际值之前进行空引用检查。
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());
}

0
  private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentCell.ColumnIndex.Equals(0))
            {
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                 enter code here
                }
            }
         }

目前你的回答不够清晰。请编辑并添加更多细节,以帮助其他人理解它如何回答所提出的问题。你可以在帮助中心找到有关如何撰写好答案的更多信息。 - Community

0

试一下这个

        if(dataGridView1.Rows.Count > 0)
            if (dataGridView1.CurrentCell.ColumnIndex == 3)
                MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接