日期:2014-05-17  浏览次数:21250 次

C#中 DataGridView的单击表头的一个错误???


DataGridView的单击表头的时候出现了一个错误:


开始的时候以为是 Dgv中没有数据项 所以有 NullReferenceException 异常:
函数:
private void DataGViewDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
           
                m_iSWId =          Convert.ToInt32(DataGViewStation.CurrentRow.Cells[8].Value.ToString());--------(异常处  NullReferenceException)
           
        }


添加判断后:
        private void DataGViewDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DataGViewStation.RowCount != 0) // --- 修改了 ;为空的Dgv 时单击表头error 
            {
                m_iSWId = Convert.ToInt32(DataGViewStation.CurrentRow.Cells[8].Value.ToString());
            }
        }
后问题不出现了。



后来;在另一Dgv中出现同样的问题:这次Dgv中有显示数据:




      private void DataGViewDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DataGViewStation.RowCount != 0) // --- 修改了 ;为空的Dgv 时单击表头error 
            {
                m_iSWId = Convert.ToInt32(DataGViewStation.CurrentRow.Cells[8].Value.ToString());------error
            }
        }

现在不清楚 原因的所在了/

  想把单元表头的事件处理去掉,不知道怎么弄。????



    
------最佳解决方案--------------------


private void DataGViewDetails_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
    {
        m_iSWId = Convert.ToInt32(DataGViewStation.CurrentRow.Cells[8].Value.ToString());
    }
}

------其他解决方案--------------------
Cells[8]这个如果是NULL,他tostring()就会出错啊~~~
------其他解决方案--------------------
出现这个问题就是空值造成的,,你调试看下吧。。。

------其他解决方案--------------------
   private void DataGViewDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DataGViewStation.RowCount != 0) // --- 修改了 ;为空的Dgv 时单击表头error