Deleting a row from a Data Table using a DGV - only works once
I have a data table that is connected to a data grid view. I want to delete the selected row from the data gird view. It works for the first time I delete a row, but when I select another row and try to delete it the program crashes as I get an "Index Out of Row exception". "There is no row at position X"
Your help would be great!
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim selectedi As Integer = dgvCustomers.CurrentCell.RowIndex
dtdgvCustomers.Rows(selectedi).Delete()
Me.Validate()
Me.objCustomersDA.Update(Me.objDataSet.Tables("tblCustomers"))
Me.objDataSet.AcceptChanges()
Refresh()
dgvCustomers.Update()
dgvCustomers.ClearSelection()
End Sub
Public Sub Retrieve()
'Clears DataSet of any existing data
objDataSet.Clear()
objCustomersDA.FillSchema(objDataSet, SchemaType.Source)
'Fills DataSet with info from DataAdapter
objCustomersDA.Fill(objDataSet)
'objDataSet.Tables.Add(dtCustomers)
dgvCustomers.DataSource = objDataSet.Tables(0)
End Sub
Re: Deleting a row from a Data Table using a DGV - only works once
I can see any number of potential problems but the most likely one is the recycling of the data adapter. Don't retain data adapters. Declare and initialise a new adapter in every sub in which you use one. It's slightly overkill but it prevents a whole bunch of inconsistencies such as the one you've now encountered.
Re: Deleting a row from a Data Table using a DGV - only works once
This line does nothing in this case:
Me.objDataSet.AcceptChanges()
so you can just remove it. Aside from that, I'd put a breakpoint on the second line and make sure that the selectedIndex is something prior to performing the delete. Without seeing the rest of the code we are all just guessing, but it may be that there just isn't a selection anymore.
Re: Deleting a row from a Data Table using a DGV - only works once
Hi Shaggy,
I put in a break point and it is receiving the correct row numbers each time. I don't understand why it won't delete the second time. Any other suggestions?
I'll try to change the DA as Dunfiddlin suggested but this might get messy.
Thanks
Re: Deleting a row from a Data Table using a DGV - only works once
I don't actually see you providing a Delete command, but if it deleted even one time then there must be one. I see no particular reason why it would delete only the one time if it is actually deleting. If you step past the delete, then you can look at the datatable and call GetChanges. That should result in a datatable that has only a single row with RowState = deleted. That might be worth a test.
I've reused dataadapters before without any problem, so I'm not convinced that's where the problem lies. Still, it doesn't look all that bad, so it may prove to be a rather obscure issue.