ASP.NET - VB.NET - How do I 1) Delete (remove) a row from a DataTable based on a value in the table and 2) How do I save the datatable changes back to the database?
Posted on 2006-04-12
I'm using a DataTable as a DataSource to my DataGrid. Until a final SAVE button is clicked, I'm keeping all changes only in the DataTable (since they may hit Cancel instead -- meaning, I don't want to commit any of their changes until the end). I've been doing fine with additions and updates, but I'm confused on how to handle deletes. This is what I have at the moment:
Sub dgMeds_DeleteRow(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
'Turn off editing:
dgMeds.EditItemIndex = -1
Dim iMedID As Integer
iMedID = dgMeds.DataKeys(e.Item.ItemIndex)
'Get DataTable from Session:
Dim objDt As New DataTable
If Not IsNothing(Session("tbl")) Then
objDt = Session("tbl")
'Delete the row with the specified medid from the DataTable in memory:
Dim iLoop As Integer
For iLoop = 0 To objDt.Rows.Count - 1
If iMedID = objDt.Rows(iLoop)("medid").ToString() Then
'Save DataTable back to Session:
Session("tbl") = objDt
'Rebind meds grid:
I'm not sure if I'm even doing this right at this point. And I've seen both Delete and also Remove for rows in a DataTable, and don't understand the difference.
I'm not getting any errors when I delete a row from my grid, using the above code, however I am getting an error when I go to ultimately save everything back to the real database:
Deleted row information cannot be accessed through the row.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.DeletedRowInaccessibleException: Deleted row information cannot be accessed through the row.
Line 1387: For intI = 0 To objDt.Rows.Count - 1
Line 1388: If objDt.Rows(intI)("medid") = 0 Then <<< offending row
Line 1389: 'NEW ROW WTIH MEDID=0 - INSERT NEW ROW:
Line 1390: Dim strSQL As String
So, what I'm gathering is that the row really isn't deleted from the DataTable, that it is just marked for deletion and that is why the error is occurring?? How can I cycle through these rows so that I can make the updates back to the database, and how can I reference a deleted row, so that I can truly delete it from the real db (in this same loop)?
Please let me know if there is more info that you need (additional code) so that my question is clear. I didn't want to overwhelm you with unnecessary code.