Able deletes rows cyclically and DataTable deletes rows cyclically.

Source: Internet
Author: User

Able deletes rows cyclically and DataTable deletes rows cyclically.

1. if you only want to delete a row in the datatable, you can use the delete Statement of DataRow. However, you must delete the row before letting the DataTable know, so you must use it. the AcceptChanges () method is used because such deletion is only for identification deletion, just like the IsDelete field we usually use in the database.

2. The. Rows. Remove (DataRow dr) method of the able will be used to completely delete the data. Similarly, only one row can be deleted. If you want to delete the data cyclically, continue to look down.

3. it is necessary to permanently delete the loop. rows. removeAt (intindex) method, so if you are a foreach enthusiast, please change your taste here, and if you are a loyal fans of for I ++, you also hope you can change your mind. Let's take a look at the forward Writing of the above Program (incorrect, unavailable)

for (int i = 0, j = dt.Rows.Count; i < j; i++)   {               if (Convert.ToInt32(dt.Rows[i]["RowID"]) == RowID)               dt.Rows.RemoveAt(i);}   

The error is that the RemoveAt () of the datatable will update the index of the dataTable after deletion. Therefore, the index you want to delete may not be consistent with Convert. toInt32 (dt. rows [I] ["RowID"]) = RowID index. In addition, an exception is thrown, indicating that the index you access does not exist. Therefore, you need to search for and delete the row from the bottom of the DataTable, so that the row above will not be affected even if the row meets the deletion conditions. The correct syntax is as follows:

protected void deleteDataRow(int RowID,DataTable dt) {       for (int i = dt.Rows.Count - 1; i >= 0; i--)      {                  if (Convert.ToInt32(dt.Rows[i]["RowID"]) == RowID)        dt.Rows.RemoveAt(i);           }   }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.