datagridview 的 cellenter 和cellLeave 事件,当激发此单元格的行列相等时,如果改变此单元格的单元格类型时,为什么会引发InvalidoperationException异常?

解决方案 »

  1.   

    可能是你当前的单元格内容值是null的,所以会报错,
    用if判断下是否为null
      

  2.   

    改变单元格类型可能从新触发CellEnter等事件,从而死循环你断点跟跟看
      

  3.   

      private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
            {
                if (dataGridView1[e.ColumnIndex, e.RowIndex].GetType() is DataGridViewComboBoxCell)
                {
                    return;
                }
                dataGridView1[e.ColumnIndex, e.RowIndex] = new DataGridViewComboBoxCell();
            }
      

  4.   

    http://topic.csdn.net/u/20080526/09/a02a618c-7c80-4e9f-af49-75e9334a702f.html
      

  5.   

    我感觉http://topic.csdn.net/u/20080526/09/a02a618c-7c80-4e9f-af49-75e9334a702f.html上说得有点问题,我观察了,只有单元格的行列相等时才引发那个异常!难道只有行列相等时才会触发_CurrentCellChanged,_CellEnter等事件,从而死循环?
      

  6.   

    建议不要用_CellEnter,个人感觉很难控制的
    改用_cellclick或者其他事件试试看
      

  7.   

    我试了以下
    改用dataGridView1_CellClick事件是可以实现的 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
            {        
                if (dataGridView1[e.ColumnIndex, e.RowIndex].GetType() is DataGridViewComboBoxCell)
                {
                    return;
                }
                dataGridView1[e.ColumnIndex, e.RowIndex] = new DataGridViewComboBoxCell();
            }
    不过用dataGridView1[e.ColumnIndex, e.RowIndex].GetType() is DataGridViewComboBoxCell判断是用问题的
    “给定表达式始终不是所提供的(“系统 System .Windows .Forms .DataGridViewComboBoxCell ”类型)”
      

  8.   

     Private Sub dataGridView2_DataError(ByVal sender As Object, _
           ByVal e As DataGridViewDataErrorEventArgs) _
           Handles DataGridView2.DataError
            Try            ' If the data source raises an exception when a cell value is 
                ' commited, display an error message.
                If e.Exception IsNot Nothing AndAlso _
                    e.Context = DataGridViewDataErrorContexts.Commit Then                MessageBox.Show("CustomerID value must be unique.")            End If        Catch ex As Exception        End Try
        End Sub
    加這個試下