Access deleted datatable rows in VB.NET
Earlier today, I was working on a VB.NET project in Visual Studio 2008 where I really needed to access fields from user deleted data-table rows before accepting changes. Here's the full story that led me to researching that action. I have a form with a DataTable that contains the result of a rather simple SQL SELECT query. This DataTable is mapped to a DataGridView control on my form. I want the user to be able to add and delete rows (among other things) without making changes to my database until the confirm their actions in bulk. Because of this, I need to access my uniqueidentifier guid field for each deleted row upon saving changes. Here's essentially how I'm accomplishing this.
For Each dr As DataRow In dt.GetChanges.Rows
If dr.RowState = DataRowState.Deleted Then
Delete(dr("ID", DataRowVersion.Original))
End If
Next
You can access all changed rows in a datatable through the table's GetChanges row collection. Each row in that collection has a "state" which indicates what action was performed on that row. In this case, I'm only interested in rows that were deleted - so I compare each row's state to DataRowState.Deleted. The tricky part is accessing the deleted row's data. The conventional means of accessing datarow fields (row.Item("FieldName")) does not work in this case. You'll get an error stating "Deleted row information cannot be accessed through the row". You need to use the row field's overloaded function and pass in DataRowVersion.Original as a parameter (row("ID", DataRowVersion.Original)). This will access the deleted row's original data. Once your program calls the AcceptChanges method on the DataTable, however, these rows will no longer be available.
Tags: .net, acceptchanges, c#, datarow, DataRowState, datatable, deleted, getchanges, rows, vb.net
Comments
Got something to say?
