我做了一个邮件收发系统,不是很成熟,邮件账户列表使用数据库的一张表绑定到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());这行代码未将对象引用设置到对象的实例请大家看看是什么问题?
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());这行代码未将对象引用设置到对象的实例请大家看看是什么问题?
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);
dataGridView1.Rows.Remove(dataGridView1.CurrentRow);上面2句换个位置,,如上
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为空,所以报出异常。建议如楼上两位大大的方法更换语句的顺序。
int strid = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString());
你先移除了当前行 这样实际上你第二句取到的是你当前选中的行的上一行数据 当有多条数据的时候不会有问题 但是最后一条数据的时候 你先移除了当前行再去取 当然就没值了 把这两行调一下位置 先取值 处理完了以后再移除