所以我在数据集(db1)中填充了这个datagridview1,并试图通过按钮删除当前选定的行。
private void delempl_Click(object sender, EventArgs e){
db1.gettable(1).Rows[dataGridView1.CurrentRow.Index].Delete()
db1.updatedb(); //sending the changes to my DB
}
每当用户更改数据网格视图中的选择时,我还会将名字/姓氏写入 2 个文本框
private void dataGridView1_SelectionChanged(){
lname.Text = db1.gettable(1).Rows[dataGridView1.CurrentRow.Index][2].ToString();
fname.Text = db1.gettable(1).Rows[dataGridView1.CurrentRow.Index][1].ToString();
}
删除最后一行工作正常,但是当我尝试删除中间的一行时,我收到以下异常:
lname.Text = db1.gettable(1).Rows[dataGridView1.CurrentRow.Index][2].ToString();
我想在删除行的那一刻,选择会发生变化并触发dataGridView1_SelectionChanged事件。
有什么方法可以解决这个问题吗?
已删除的行仍存在于数据表中,但您无法读取其属性。
您应该检查当前行是否已删除
private void dataGridView1_SelectionChanged()
{
DataTable tb = db1.gettable(1);
if(dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.Index != -1 &&
tb[dataGridView1.CurrentRow.Index].RowState != DataRowState.Deleted)
{
lname.Text = tb.Rows[dataGridView1.CurrentRow.Index][2].ToString();
fname.Text = tb.Rows[dataGridView1.CurrentRow.Index][1].ToString();
}
}