Reputation: 183
So i have this datagridview1 filled with a datatable(index 1) in a dataset(db1) and im trying to delete the currently selected row via Button.
private void delempl_Click(object sender, EventArgs e){
db1.gettable(1).Rows[dataGridView1.CurrentRow.Index].Delete()
db1.updatedb(); //sending the changes to my DB
}
I also write the first/lastname into 2 textboxes whenever the selection in the datagridview is changed by the user
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();
}
Deleting the last row works fine but when i try to delete one in the middle i get an DeletedRowInaccessible Exception on:
lname.Text = db1.gettable(1).Rows[dataGridView1.CurrentRow.Index][2].ToString();
I guess the moment the row gets deleted, the selection changes and triggers the dataGridView1_SelectionChanged-Event.
Any way to fix that?
Upvotes: 2
Views: 2323
Reputation: 216313
A deleted row is still present in the datatable but you can't read its properties.
You should check if the CurrentRow is deleted or not
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();
}
}
Upvotes: 4