Delete the row of the datatable

Source: Internet
Author: User
When you use datatable. Rows [I]. Delete () to Delete a row and then access the table, the error "cannot access the information of the row deleted" appears. The reason is as follows:

The datatable is required after the Delete () operation. the AccepteChanges () method confirms that the data is completely deleted. Because Delete () only marks the status of the corresponding column as deleted, you can also use datatable. the RejectChanges () rollback cancels the deletion of this row.

Therefore, to completely Delete datarow, you must use both the Delete () and AccepteChanges () methods, or use datatable. rows. the RemoveAt (I) method is directly deleted, where I indicates the row index and a datatable. rows. remove (DataRow dr) deletes a specified row.

However, use datatable. rows. removeAt (I) should note that if the able is used continuously. rows. removeAt (0); datatable. rows. removeAt (1); in this case, the row 0 in the original table is not deleted, but after the row 0 is deleted, the original Row 1 is changed to 0, so the datatable. rows. removeAt (1) actually deletes two rows of the original table.

Therefore, you should use datatable. Rows. RemoveAt (I) with caution. To Delete multiple Rows, you can use Delete () consecutively and then use the AccepteChanges () method to confirm the deletion.

 

Code Public DataTable GetUserByMonth (string month)
{
DataTable dtUser = GetList ("paymonth> 0 and paymonth <" + month). Tables [0];

For (int I = 0; I <dtUser. Rows. Count; I ++)
{
Decimal Number = (Decimal) dtUser. Rows [I] ["Telenbr"];
Decimal Other = (Decimal) dtUser. Rows [I] ["other"];
Decimal Sum = 0.0 M;
Sum = HFdal. GetQianfei (dtUser. Rows [I] ["paymonth"]. ToString (), month, Number );
If (Other <Sum)
{
DtUser. Rows [I] ["Define3"] = Sum;
DtUser. Rows [I] ["Define4"] = Other-Sum;
}
Else
{
DtUser. Rows [I]. Delete ();
}
}
DtUser. AcceptChanges ();
Return dtUser;
}

 

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.