Operating data in ASP.net 2.0 63: GridView Implementation of Bulk Delete data _ self-study process

Source: Internet
Author: User
Tags foreach

Introduction:

In the previous tutorial, we created a batch editing interface with the GridView. The batch editing interface is useful when users need to edit multiple records at once. Similarly, this technique is also useful when users need to delete more than one record at a time.

If you've ever used a mail system, you should be familiar with this most common batch removal interface: Each row in the interface contains a checkbox, plus a delete all Checked Items button (Figure 1). This tutorial is relatively short, Since we have completed the general framework in the previous tutorial, in the previous 50th chapter "Adding a checkbox for the GridView control" we created a GridView control containing a checkboxes column, and in Chapter 61, "Encapsulation of database modifications in a transaction", We created a method in the BLL business logic layer that uses transactions to delete ProductID based records. In this tutorial, we will consolidate these to create an example of processing batch deletions.


Figure 1: Each row contains a checkbox

First step: Create a batch delete interface

Since we have created a batch deletion interface in chapter 52nd, we can simply copy it to the Batchdelete.aspx page. First, open the Batchdelete.aspx page in the Batchdata folder and the Checkboxfield.aspx page in the Enhancedgridview folder. On the checkboxfield.aspx page, switch to source mode and copy the code from the <asp:Content> tag.


Figure 2: Copy the Declaration code from the checkboxfield.aspx page

Then, switch to the source mode of the Batchdelete.aspx page and paste the code into the <asp:Content> Tag. In the same vein, copy the background code from the CheckBoxField.aspx.cs inside the BatchDelete.aspx.cs. (Specifically, the Click event event for the Deleteselectedproducts button, the Togglecheckstate method, the Checkall, and the Uncheckall button). After the copy is complete, the background code class for the Batchdelete.aspx page should contain the following code:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;

Using System.Web.UI.HtmlControls; Public partial class BatchData_BatchDelete:System.Web.UI.Page {protected void Deleteselectedproducts_click (Object sen

 Der, EventArgs e) {bool atleastonerowdeleted = false; Iterate through the Products.rows property foreach (GridViewRow row in products.rows) {//Access the CheckBox Chec Kbox cb = (CheckBox) row.
 FindControl ("Productselector"); if (CB!= NULL && CB. Checked) {//Delete row!
 (OK, not really ...)

 Atleastonerowdeleted = true; The ProductID for the selected row int ProductID = Convert.ToInt32 (products.datakeys[row. RowIndex].

 Value); The "Delete" row Deleteresults.text + = string.

 Format ("This would have deleted ProductID {0}<br/>", ProductID); //... to actualLY deletes the product, use ...//productsbll productapi = new PRODUCTSBLL ();
 Productapi.deleteproduct (ProductID);
 //............................................
 }
 //Show the Label if at least one row is deleted ...
 deleteresults.visible = atleastonerowdeleted;  } private void Togglecheckstate (bool checkstate) {//Iterate through the Products.rows property foreach (GridViewRow Row in products.rows) {//Access the checkbox checkbox cb = (CheckBox) row.
 FindControl ("Productselector"); if (CB!= NULL) CB.
 Checked = CheckState;
 } protected void Checkall_click (object sender, EventArgs e) {togglecheckstate (true);
 } protected void Uncheckall_click (object sender, EventArgs e) {togglecheckstate (false);

 }
}

After completing the above work, take a few minutes to test the page in the browser. You should first see a GridView control lists the first 10 products, each row lists the product name, Category,price, and a checkbox. There should also be 3 buttons "Check All" and "uncheck All" and "Delete Selected products." The point "check All" button will select all the checkboxes and the "uncheck All" button will release all the
Checkboxes Point "Delete Selected products" displays a message that lists the ProductID value of the selected product, but does not actually delete the product.


Figure 3:checkboxfield.aspx The interface of the page moved to the batchdeleting.aspx page

Step Two: Delete the selected product in the transaction

After completing the interface, the remaining thing is to update the code so that when you click the "Delete Selected Products" button, use the PRODUCTSBLL Class class in the Deleteproductswithtransaction method to delete the selected product. The method is added in the 61st chapter, "Encapsulation of database modifications in transactions," which accepts a series of ProductID values, The corresponding ProductID record is then deleted in a transaction.

The Deleteselectedproducts button's Click event currently uses the Foreach Loop as follows:

Iterate through the Products.rows property
foreach (GridViewRow row in products.rows)
{
 //Access the Check Box
 checkbox cb = (checkbox) row. FindControl ("Productselector");
 if (CB!= NULL && CB. Checked)
 {
 //Delete row! (OK, not really ...)
 Atleastonerowdeleted = true;

 The ProductID for the selected row
 int ProductID = Convert.ToInt32 (products.datakeys[row. RowIndex]. Value);

 The "Delete" row
 deleteresults.text + = string. Format
 ("This would have deleted ProductID {0}<br/>", ProductID);

 //... To actually deletes the product, use ...
 PRODUCTSBLL Productapi = new Productsbll ();
 Productapi.deleteproduct (ProductID);
 //............................................
 }
}

For each line, the programmatic Reference Productselector checkbox control, if it is selected, gets the ProductID value of the product from the DataKeys collection set, Then update the Text property of the Deleteresults control to show that you want to delete the row.

The above code does not really delete any records, because in the PRODUCTSBLL class we just annotate how to use the Delete method. However, even if the deletion logic is actually used, the code can delete the product but does not use atomic operations. That is, if the following product is deleted successfully, if the subsequent deletion fails (for example, it may be a violation of the inside-key constraint), then an exception will be thrown. However, the previous delete operation does not roll back.

To ensure the use of atomic operations, we will switch to the Deleteproductswithtransaction method using the Productsbllclass class. Because the method accepts a series of ProductID values,
We first need to compile this series of values and pass them as arguments. We first create an instance of list<t> of type int, in which we need to add the ProductID value of the product to the LIST<T> List<t> will be passed to the Deleteproductswithtransaction method of the Productsbll class classes, Update the Click event handler for the Deleteselectedproducts button with the following code:

protected void Deleteselectedproducts_click (object sender, EventArgs e) {//Create a List to hold the ProductID values To delete system.collections.generic.list<int> Productidstodelete = new System.collections.generic.list<int

 > (); Iterate through the Products.rows property foreach (GridViewRow row in products.rows) {//Access the CheckBox Chec Kbox cb = (CheckBox) row.
 FindControl ("Productselector"); if (CB!= NULL && CB. Checked) {//Save the ProductID value for deletion//I, get the ProductID for the selected row int ProductID = C Onvert. ToInt32 (Products.datakeys[row. RowIndex].

 Value);

 Add it to the List ... productidstodelete.add (ProductID); ADD a confirmation message Deleteresults.text + = string.
 Format ("ProductID {0} has been deleted<br/>", ProductID); }//Call the Deleteproductswithtransaction method and show the Label//if at least one row is deleted ... if (pro Ductidstodelete.count > 0) {productsbll prodUctapi = new PRODUCTSBLL ();

 Productapi.deleteproductswithtransaction (Productidstodelete);

 Deleteresults.visible = true;
 Rebind the data to the GridView products.databind ();

 }
}

The above code creates an int type list<t> (that is, productidstodelete) and fills it with a ProductID value, and when the Foreach loop ends, if at least one product is selected, the PRODUCTSBLL is invoked Class by Deleteproductswithtransaction method and passing the list. The label control named Deleteresults is also displayed; The data is rebind to the GridView (naturally, records that have just been deleted will not be displayed).

In Figure 4, we select several products to delete; Figure 5 shows the click "Delete Selected Product" The interface after the button. Note that the ProductID value of the deleted product displayed in the Label control, which has been deleted, does not appear in the GridView control.


Figure 4: The selected product will be deleted


Figure 5: The ProductID value of the deleted product appears in the label control below the GridView

  Note: To verify the atomic operation of the Deleteproductswithtransaction method, you can manually add an entry to a product in the order details, and then try to delete the product (which, of course, is deleted with other products). This will violate the FOREIGN KEY constraint and notice how the deletion of other products is rolled back.

Summarize:

To create a batch deletion interface, we need to create a GridView control that contains the checkboxes column, and a button Web control. When we click on this button, we will delete multiple products as a single atom operation. In this article, we create an interface that integrates the previous 2 chapters.

In the next article, we examine how to create a batch-inserted interface

I wish you a happy programming!

Introduction of the author

The author of this series of tutorials, Scott Mitchell, has six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. You can click to see all Tutorials "[translation]scott Mitchell asp.net 2.0 data tutorial," I hope to learn asp.net help.

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.