我做了一个邮件收发系统,不是很成熟,邮件账户列表使用数据库的一张表绑定到datagridview控件,删除一行数据的操作,我是这样写的 :
    dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
    int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString());
      MessageDataContext mdc = new MessageDataContext();
           //linq to sql创建的实体类,调用存贮过程
               mdc.ddo_Delete(strid);
               mdc.SubmitChanges(); 
当删除最后一条数据时提示:
int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());这行代码未将对象引用设置到对象的实例请大家看看是什么问题?

解决方案 »

  1.   

    dataGridView1.CurrentRow.Cells[0].Value.ToString()确认这里面有没有值,如果是NULL肯定会报错。
      

  2.   

    得到值再移除看看
    dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
      int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString());
    =》
    int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString());
    dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
      
      

  3.   

      int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString()); 
     dataGridView1.Rows.Remove(dataGridView1.CurrentRow);上面2句换个位置,,如上
      

  4.   

     dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
      int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString());
      MessageDataContext mdc = new MessageDataContext();
      //linq to sql创建的实体类,调用存贮过程
      mdc.ddo_Delete(strid);
      mdc.SubmitChanges();  
    执行dataGridView1.Rows.Remove(dataGridView1.CurrentRow)删除最后一行时,执行完的时候dataGridView1中没有数据,所以dataGridView1.CurrentRow为空,所以报出异常。建议如楼上两位大大的方法更换语句的顺序。
      

  5.   

    dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
      int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString());
    你先移除了当前行 这样实际上你第二句取到的是你当前选中的行的上一行数据  当有多条数据的时候不会有问题 但是最后一条数据的时候 你先移除了当前行再去取 当然就没值了   把这两行调一下位置 先取值  处理完了以后再移除 
      

  6.   

    更新删除数据库中的数据是 Delete 方法,通过 Delete 方法删除的 Row 将会被标记,但不会被真正的从 DataTable 中删除,Remove 是直接将 Row 从 DataTable 中删除,当 Table Update 的时候,数据库中对应的数据根本不会有任何变动。所以你 Remove 之后再去取值,是会报错的,你应该先 Delete,然后在取值就没有问题。而且 Remove 对于数据的更新也不正确。