Manipulating data in ASP.net 2.0 50: Adding Checkbox_ to the GridView control self-study process

Source: Internet
Author: User
Tags visual studio

Introduction:

In the previous tutorial we explored how to add radio buttons columns to the GridView control. When the user can select at most one data, we can add radio buttons columns in the user interface, and sometimes we need to select any number of data. For example, a web-based mailbox client lists a list of messages, and a list of checkboxes, in which the user can select any message and perform the same action, such as moving to another folder or deleting it.

In this tutorial, we'll explore how to add checkboxes columns, and how to determine which checkboxes to choose after a page return occurs. In particular, we'll practice a web-based mailbox client user interface. The instance will contain a GridView with paging enabled to list the products in the table product and each row contains a checkbox (see Figure 1). When you click the "Delete Selected products" button, delete the selected product.


Figure 1: Each product row contains a checkbox

Step 1th: Add a GridView control that enables pagination to display product information

Before considering adding a checkboxes column, we first create a GridView control that displays the product and enable paging. Open the Checkboxfield.aspx page in the folder Enhancedgridview and enter design mode, drag a GridView from the toolbox to the page, and set its ID to products. Next, bind it to a ObjectDataSource control named Productsdatasource. The ObjectDataSource control uses the PRODUCTSBLL class to invoke the GetProducts () method to return data. Because the GridView control for this example is read-only, select (None) in the Drop-down list on the update, insert, and Delete tabs.


Figure 2: Creating a ObjectDataSource control named Productsdatasource


Figure 3: Setting the ObjectDataSource control calls the GetProducts () method to get the data


Figure 4: Select (None) in the Drop-down list on the update, insert, and Delete tabs.

When the settings are complete, Visual Studio automatically creates boundcolumns and a checkboxcolumn for the relevant data field (fields). As we did in the previous tutorial, we remove other boundfields except ProductName, CategoryName, and UnitPrice, and set the associated HeaderText property to "Product", "Category", and "Price". Format the UnitPrice BoundField as currency. Select "Enable paging" on the smart tag to enable the GridView paging feature.

In order to remove the selected product from the user interface, add a button Web control under the GridView, with its ID Deleteselectedproducts,text property to "delete Selected products." In this example we do not delete data directly from the database, but instead display a message stating what product is being deleted. Therefore, add a label Web control under the button, set its ID to Deleteresults, empty its Text property, and set the visible and EnableViewState properties to false.

After you have done this, the GridView, ObjectDataSource, button, and label declaration code should be similar to the following:

<p> <asp:gridview id= "Products" runat= "server" autogeneratecolumns= "False" datakeynames= "ProductID" Datasourceid= "Productsdatasource" allowpaging= "True" enableviewstate= "False" > <Columns> <asp:boundfiel D datafield= "ProductName" headertext= "Product" sortexpression= "ProductName"/> <asp:boundfield datafield= "Cat Egoryname "headertext=" Category "readonly=" True "sortexpression=" CategoryName "/> <asp:boundfield" DataField= " UnitPrice "dataformatstring=" {0:c} "headertext=" Price "htmlencode=" False "sortexpression=" UnitPrice "/> </
  columns> </asp:GridView> <asp:objectdatasource id= "Productsdatasource" runat= "Server" oldvaluesparameterformatstring= "original_{0}" selectmethod= "GetProducts" typename= "ProductsBLL" > </asp:O bjectdatasource> </p> <p> <asp:button id= "deleteselectedproducts" runat= "Server" text= "Delete Selected Products "/> </p> <p> <asp:label id=" DEleteresults "runat=" server "enableviewstate= false" visible= "false" ></asp:Label> </p>
 

Take a few minutes to view the page in the browser (see Figure 5), and you can see the top 10 Product name, category, and price.


Figure 5: Display name, category, and price for the top 10 products

Step 2nd: Add a checkboxes column

Since ASP.net 2.0 contains a CheckBoxField, we might naturally think of using it to add a checkboxes column to the GridView control. However, that is not the case. Because CheckBoxField is specifically designed to deal with Boolean data fields (Boolean field).
In other words, when the value of the data field can be used to determine whether a checkbox is selected, CheckBoxField is useful. CheckBoxField cannot correctly contain a column of unselected checkboxes.

As a replacement, we have to add a template and add a CheckBox Web control to its ItemTemplate mode. We're going to add a template to the GridView control products and put it on the far left. In the GridView smart tag, click Edit Template, add a CheckBox Web Control in ItemTemplate mode, and set its ID to productselector.


Figure 6: Adding a CheckBox Web control named Productselector in the template's ItemTemplate mode

After you add a template and a CheckBox Web control, each row of records will contain a CheckBox button, as shown in Figure 7:


Figure 7: Each product line contains a CheckBox button

3rd step: After the page return to determine which checkboxes button clicked

Now we've created a checkboxes column, but we're not sure which checkboxes buttons to click after the page comes back, but when we click on the "Delete Selected Products" button, we need to determine which product to remove. Which checkboxes buttons are clicked.

We can use the Rows property of the GridView to access its data rows, which programmatically access the CheckBox control of the record row, depending on its checked property to determine whether the button is selected.

Create an event handler for the Click event of the button Web control named Deleteselectedproducts, adding the following code:

 protected void Deleteselectedproducts_click (object sender, EventArgs e) {bool Atleas

 tonerowdeleted = false; Iterate through the Products.rows property foreach (GridViewRow row in products.rows) {//Access the CheckBox Ch Eckbox 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);
 }//Show the Label if at least one row is deleted ...
deleteresults.visible = atleastonerowdeleted; }

The Rows property of the GridView control returns a collection of GridViewRow instances that compose the GridView data row. The foreach () loop loops through each instance of the collection. In a GridViewRow object, we use row. FindControl ("ControlID") to access the checkbox button for the row record. If the button is selected, the ProductID value corresponding to that row record is fetched from the DataKeys collection.

In this case, we just display the relevant hints in the Label control Deleteresults, and in the actual application we should call the Deleteproduct (ProductID) method of the Productsbll class.

After adding the event handler above, clicking the "Delete Selected Products" button will show the ProductID value of the selected product.


Figure 8: When the "Delete Selected products" is clicked, the ProductID value of the selected product is listed

Step 4th: Add the Check all and uncheck all buttons

If the user wants to delete all the products on the current page, you must click the checkbox button for each row, slightly
Obvious trouble. We can add a check All button to select all the checkbox buttons on the page when you click the button. Instead, add a "uncheck All" button.

Add 2 button Web controls on the page, above the GridView. Set the first ID to Checkall,text property to "Check all"; Set the second ID to Uncheckall,text property to "uncheck All", as follows:

<asp:button id= "Checkall" runat= "text=" Check all "/> <asp:button id=" Uncheckall "runat="
Server "text=" uncheck All "/>

Next, create a method named Togglecheckstate (CheckState) in the Background code class (Code-behind Class). When this method is invoked, it iterates through the rows collection of the GridView control products, assigning values to the Checked property of each checkbox based on the parameters passed in. checkstate

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;
 }


Then, create the Click event handler for the button control Checkall and Uncheckall, and simply invoke Togglecheckstate (true) in the Checkall click event handler; In the Uncheckall event handler, call Togglecheckstate (FALSE) as follows:

protected void Checkall_click (object sender, EventArgs e)
{
 togglecheckstate (true);
}

protected void Uncheckall_click (object sender, EventArgs e)
{
 togglecheckstate (false);
}

When the "Check All" button is clicked, the page is returned and all checkbox buttons are selected, and all checkbox buttons are discarded when you click "Uncheck All". Figure 9 is the interface after clicking the "Check All" button.


Figure 9: Click the Check All button to select all the checkbox

  Note: If you want to select or discard the checkbox button, we can do so by clicking on the checkbox of the header row (header row) and the page will not take effect until it has been turned back. Using client-side scripting (Client-side script) entirely to perform the Select or Discard checkbox buttons is a much more refreshing user experience.

Summarize:

When the user needs to select any record in the GridView, we can add a list of checkbox press buttons. As explored in this chapter, add a template to the GridView and add a CheckBox Web control to the template. If you use a Web control (in contrast to the previous chapter, we inject the code directly into the template), after the page has turned around, the ASP. NET automatically remembers which checkbox controls are selected or not selected. We can also programmatically access these checkbox to determine whether a checkbox is selected or to change its checked state.

I wish you a happy programming!

Author Introduction

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.