C#--Delete a row in DataTable

In C#, if you want to delete a row in DataTable, there are several ways:
1. Use DataTable.Rows.Remove(DataRow) or DataTable.Rows.RemoveAt(index); you can directly delete row
2, datatable. Rows[i]. Delete(). After Delete(), the datatable.AccepteChanges() method is required to confirm the complete deletion, because
Delete() just marks the status of the corresponding column as deleted, and can also be rolled back through datatable.RejectChanges() to cancel the deletion of the row.
The effect of delete is as follows:
insert image description here
3. When deleting rows in DataTable, every time a row is deleted, the indexes of all rows in DataTable will change. Foreach cannot be used while looping to delete
DataTable.Row. When using foreach for looping, table deletion and addition operations are not allowed.
4. If the deletion is based on a certain column, the index of the entire Table will change immediately after each row is deleted, which means that the Table has become a new table. But the index has been increased by 1. This will cause the first column to never match. Therefore, every time a row is deleted, it is necessary to determine whether the first row meets the deletion condition.
If you want to delete multiple rows in DataTable, you should cycle DataTable.Rows in reverse order. Because the index will change when deleting in positive order. The program is abnormal, and it is difficult to predict the consequences.
insert image description here
Summarize:

delete and remove
The use of Delete is datatable.Rows[i].Delete();
the use of Remove is datatable.Rows.Remove(datatable.Rows[i]);
the difference between the two is that after using delete, only the row It is marked as deleted, but it still exists. When using Rows.Count to get the number of rows, the
previous number of rows is still deleted. You need to use the datatable.AcceptChanges() method to submit the modification.
The Remove method is to delete directly.
If in for If you delete rows in the loop, it is best to use the delete method, otherwise the count will change. After the loop is complete, use the
AcceptChanges() method to submit the modification and delete the row marked as deleted. The
actual usage is as follows:

insert image description here

Guess you like

Origin blog.csdn.net/weixin_41883890/article/details/128966570