Storing Data in Memory in Microsoft ADO.NET 4
You remove DataRow objects from a table via the DataTable.Rows collection’s Remove and RemoveAt methods. The Remove method accepts an instance of a row that is currently in the table.
C# DataRow oneRow = someTable.Rows; someTable.Rows.Remove(oneRow); Visual Basic Dim oneRow As DataRow = someTable.Rows(0) someTable.Rows.Remove(oneRow)
The RemoveAt method also removes a row, but you pass it the index position of the row to delete.
C# someTable.Rows.RemoveAt(0); Visual Basic someTable.Rows.RemoveAt(0)
If you have an instance of a data row available, but you want to call the RemoveAt method, you can obtain the index of the row from the Rows collection’s IndexOf method.
C# int rowPosition = someTable.Rows.IndexOf(oneRow); Visual Basic Dim rowPosition As Integer = someTable.Rows.IndexOf(oneRow)
You can put any row you remove from a table right back into the Rows collection by using the standard DataTable.Rows.Add method. Another Rows method, InsertAt, adds a DataRow object to a table, but lets you indicate the zero-based position of the newly added row. (The Add method always puts new rows at the end of the collection.) The following code inserts a row as the first item in the collection:
C# someTable.Rows.InsertAt(oneRow, 0); Visual Basic someTable.Rows.InsertAt(oneRow, 0)
To remove all rows from a table at once, use the DataTable.Rows object’s Clear method.
C# someTable.Rows.Clear(); Visual Basic someTable.Rows.Clear()
As convenient as Remove, RemoveAt, and Clear are, they come with some negative side effects. Because they fully remove a row and all evidence that it ever existed, these methods prevent ADO.NET from performing certain actions, including managing record removes within an external database. The next section, Batch Processing, discusses a better method of removing data records from a DataTable instance.