【问题标题】:datagridview cell click eventdatagridview 单元格点击事件
【发布时间】:2012-09-27 12:59:51
【问题描述】:

我有一个数据网格视图中的单元格单击事件,以在消息框中显示单击的单元格中的数据。我将其设置为仅适用于某一列且仅在单元格中有数据时才有效的位置

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

但是,每当我单击任何列标题时,都会显示一个空白消息框。我不知道为什么,有什么提示吗?

【问题讨论】:

    标签: c# datagridview cell


    【解决方案1】:

    您还需要检查单击的单元格不是列标题单元格。像这样:

    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 ` ...
    【解决方案2】:

    检查CurrentCell.RowIndex 不是标题行索引。

    【讨论】:

      【解决方案3】:
      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());
      }
      

      【讨论】:

        【解决方案4】:

        接受的解决方案会引发“对象未设置为对象的实例”异常,因为空引用检查必须在检查变量的实际值之前进行。

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

        【讨论】:

          【解决方案5】:

          试试这个

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

          【讨论】:

            猜你喜欢
            • 2015-09-25
            • 2021-02-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-01
            • 2011-11-29
            相关资源
            最近更新 更多