Introduction to the difference between the Delete and Remove methods for deleting rows by Datatable

  • 2020-06-01 09:19:42
  • OfStack

1. If you want to delete a line from DataTable in C#, you can do the following:

The & # 8226; DataTable.Rows.Remove (DataRow), or DataTable.Rows.RemoveAt (index); You can delete rows directly
The & # 8226; datatable. Rows [i] Delete (). After Delete() you need the datatable.AccepteChanges () method to confirm the full deletion, because Delete() simply marks the status of the corresponding column as deleted, or you can roll back the row by datatable.RejectChanges () to cancel the deletion.
The & # 8226; When a row in DataTable is deleted, the index of all rows in DataTable changes for each row deleted. foreach cannot be used when looping DataTable.Row. When using foreach for looping, Table is not allowed to have delete and add operations.
The & # 8226; If a row is deleted according to a certain column condition, the index of the entire Table will change immediately after each row is deleted, which is equal to that Table has become a new table. But the index has already been incremented by 1. So column 1 will never match. Therefore, for every row that is deleted, it is necessary to determine whether the first row satisfies the deletion condition.
The & # 8226; If you want to delete multiple lines in DataTable, you should use the reverse loop DataTable.Rows. Because the index changes when the positive order is dropped. Program exception, it is difficult to predict the consequences.

Conclusion:

delete and remove

The & # 8226; The use of Delete is datatable. Rows[i].Delete();
The & # 8226; The use of Remove is datatable.Rows.Remove (datatable.Rows [i]);
The & # 8226; The difference between the two is that when delete is used, only the row is marked as deleted, but it still exists that when the row number is obtained with Rows.Count, the previous row number is still deleted. You need to use the datatable.AcceptChanges () method to commit the change.
The & # 8226; The Remove method simply deletes.
The & # 8226; If you delete a row in an for loop, it is best to use the delete method, otherwise you will see a change in count. After the loop is over, use the AcceptChanges() method to commit the change and delete the row marked deleted


Related articles: