Operating data in ASP.net 2.0 37: DataList Batch Update _ self-study process

Source: Internet
Author: User
Tags eval

Introduction

In the front we learned how to create item-level DataList. As with the editable GridView, the item in each DataList contains an Edit button, and when clicked, the item becomes editable. Item-level edits are fine when updates are occasionally needed, but in some cases the user needs to edit a large number of records. If a user needs to edit a lot of records, he will be forced to keep clicking Edit, making changes, and clicking Update, which will hinder his productivity. In this case, a good choice is to provide a fully editable DataList, all of its item is in edit mode, all of its values can be updated by clicking on an "Update all" button. See Figure 1.


Figure 1: All item of a fully editable DataList can be modified

In this chapter, we'll learn how to create a fully editable DataList that provides users with the ability to update supplier's address.

First step: Create an editable user interface in DataList ItemTemplate

When we first created a standard item-level edit DataList, we used two template:

itemtemplate-contains a read-only user interface (displays the name and price of each product using a Label).
edititemtemplate-contains the edited user interface (two textbox).

The DataList EditItemIndex attribute indicates which DataListItem uses EditItemTemplate to show (if any). That is, the value of ItemIndex is equal to DataList's EditItemIndex DataListItem use EditItemTemplate to show. This pattern works well in the case of editing only one item at a time, but it does not apply when creating fully editable DataList.

For fully editable DataList, we need all the DataListItem to be shown in an editable interface. The easiest way to do this is to define an editable interface in the ItemTemplate. For modifying supplier address information, supplier in the editable interface are displayed as text, and address,city and country values are represented by a textbox.

First open the Batchupdate.aspx page, add a DataList, and set the ID to suppliers. Add a ObjectDataSource control named Suppliersdatasource through the smart tag.


Figure 2: Creating a ObjectDataSource named Suppliersdatasource

Use the Getsuppliers () method of the SUPPLIERSBLL class to configure the ObjectDataSource (see Figure 3). As in the previous chapter, we will update supplier information directly using BLL instead of ObjectDataSource. Select None in the Update tab (see Figure 4).


Figure 3: Configuring ObjectDataSource using the Getsuppliers () method


Figure 4: Set update label to none

When you complete the wizard, Visual Studio automatically generates DataList ItemTemplate to display each data field in the label. We need to modify this template so that it provides an editing interface. ItemTemplate can be defined in the designer by using the edit templates or direct write declaration syntax on the DataList smart tag.

Create an editing interface that displays the name of supplier as text, Address,city, and Country as a TextBox. After you have done this, your declaration code should be similar to the following:

<asp:datalist id= "Suppliers" runat= "Server" datakeyfield= "SupplierID" datasourceid= "Suppliersdatasource" > <ItemTemplate>  

  Note: As in the previous chapter, you need to open view state for DataList.

In ItemTemplate I used two new CSS classes, Supplierpropertylabel and Supplierpropertyvalue. Their style settings are the same as Productspropertylabel and Productpropertyvalue CSS classes and have been added to the styles.css.

. Productpropertylabel,. Supplierpropertylabel
{
 font-weight:bold;
 Text-align:right
}
. Productpropertyvalue,. Supplierpropertyvalue
{
 padding-right:35px;
}

When you are done, browse the page. As shown in Figure 5, each DataList item displays supplier name in text, and address,city and country are displayed in a TextBox.


each supplier in the figure 5:datalist can be edited

Step Two: Add the "Update all" button

The information shown in Figure 5 does not provide the Update button for the time being. The fully editable DataList should contain only an "Update all" button, not one button per item, as before. All records in the DataList will be updated when you click "Update All". In this chapter we will add two "Update all" button-one above the page, one below (two provide the same functionality).

First, add a button with an ID of UpdateAll1 above the DataList. Then add the button with the ID UpdataAll2 under DataList. The text of the two button is set to "Update all". Finally, an event handler is created for the Click event of the two button. We create a method, "Updateallsupplieraddress", and then call it in event handling. (instead of copying the same code in two event processing)

protected void Updateall1_click (object sender, EventArgs e)
{
 updateallsupplieraddresses ();
}
protected void Updateall2_click (object sender, EventArgs e)
{
 updateallsupplieraddresses ();
}
private void Updateallsupplieraddresses ()
{
 //Todo:write code to update _all_ of the supplier addresses in the DataList
}

Figure 6 is the page after the "Update all" button has been added.


Figure 6: The page has added two "Update all" button

Step three: Update all suppliers address information

Having finished displaying all of the item as an editable interface and adding the "Update all" button, the rest is writing code to perform a batch update. We need to facilitate the DataList item and call the Updatesupplieraddress method of the Suppliersbll class.

The

can access the DataListItem collection through the DataList Items property. Using the DataListItem reference, we can get the relevant Suppliserid from the DataKeys collection and reference the textbox in ItemTemplate, see the following code:

private void Updateallsupplieraddresses () {//Create an instance of the Suppliersbll class SUPPLIERSBLL Suppliersapi =
 New SUPPLIERSBLL (); Iterate through the DataList ' s items foreach (DataListItem item in Suppliers.items) {//Get the SupplierID from th e DataKeys Collection int supplierID = Convert.ToInt32 (Suppliers.datakeys[item.
  ItemIndex]); Read in the user-entered values TextBox address = (TextBox) item.
  FindControl ("Address"); TextBox city = (textbox) item.
  FindControl ("City"); TextBox country = (textbox) item.
  FindControl ("Country");
  String addressvalue = null, Cityvalue = NULL, Countryvalue = NULL; if (address. Text.trim (). Length > 0) addressvalue = address.
  Text.trim (); if (city. Text.trim (). Length > 0) cityvalue = city.
  Text.trim (); if (country. Text.trim (). Length > 0) countryvalue = country.
  Text.trim (); Call the Suppliersbll class ' s updatesupplieraddress to Suppliersapi.updatesupplieraddress (SupplierID, address Value, CITYvalue, Countryvalue);
 }
}

When the user clicks on an "Update all" button, each DataListItem in the supplier DataList executes the Updateallsupplieraddress method. and call the Updatesupplieraddress method of the SUPPLIERSBLL class to pass the relevant values over. If a value is not entered in address,city or country, updatesupplieraddress receives a null value (not an empty string), and the result of the associated field is a database NULL.

  Note: You can add a display status label to provide some confirmation information when the batch update is complete. Update only records that have been modified by addresses

The batch update rule used in this chapter invokes the Updatesupplieraddress method for supplier in each DataList, regardless of whether the address information has been modified. Although this blind update generally does not have any performance problems, but if you have a database table audit, it will lead to a lot of redundant records. Each time the user clicks on the "Update All" button, the system creates a new audit record for each supplier, regardless of whether the user has any changes.

Ado. NET Datetable and DataAdapter classes are designed to support batch updates of records that are only modified, deleted, or added. Each row of the DataTable has a RowState property to indicate whether the row was added to the DataTable or deleted from it, modified, or unchanged. When the DataTable is first created, all the rows are marked unmodified, and the row is marked as modified after any column that modifies the row.

In the SUPPLIERSBLL class we first read the supplier records into the suppliersdatatable and then set the address,city and Country column values to update the specified supplier information, see the following code:

 public bool Updatesupplieraddress (int SupplierID, string address, string city, Strin
 G country) {northwind.suppliersdatatable suppliers = Adapter.getsupplierbysupplierid (SupplierID); if (suppliers.
 Count = = 0)//No matching record found and return false to false;
  else {Northwind.suppliersrow supplier = suppliers[0]; if (address = = null) supplier.
  Setaddressnull (); else supplier.
  address = address; if (city = = null) supplier.
  Setcitynull (); else supplier.
  City = city; if (country = = null) supplier.
  Setcountrynull (); else supplier.
  Country = Country;
  Update the supplier address-related information int rowsaffected = adapter.update (supplier);
 Return true if precisely one row is updated,//otherwise false return rowsaffected = = 1; }
}

This code assigns the values of the incoming address,city and country to the suppliersrow of suppliersdatatable, regardless of whether the value has been modified. This modification will cause the Suppliersrow RowState attribute to be marked as modified. When the DAL's Update method is invoked, it finds that the Supplierrow has been modified, so the update command is sent to the database.

Imagine, however, that the code we add for this method only assigns the value of the incoming address,city and country to suppliersrow only if it is not the same as the existing value. In cases where address,city and country are not modified, the RowState of the Supplierrow is still marked unchanged. The result is that when the DAL's Update method is invoked, the Suppliersrow is not modified, so the database is not invoked. Use the following code instead of the blind assignment in front:

Only assign the values to the Supplierrow ' s column values if they differ
if (address = = NULL &&!supplier.i Saddressnull ())
 supplier. Setaddressnull ();
else if (address!= null && supplier. Isaddressnull ()) | |
   (!supplier. Isaddressnull () &&
   string.compare (supplier. Address, address)!= 0)
 supplier. address = address;
If City = = null &&!supplier. Iscitynull ())
 supplier. Setcitynull ();
else if (city!= null && supplier. Iscitynull ()) | |
   (!supplier. Iscitynull () && string.compare (supplier. City, City)!= (0))
 supplier. City = city;
if (country = = NULL &&!supplier. Iscountrynull ())
 supplier. Setcountrynull ();
else if (country!= null && supplier. Iscountrynull ()) | |
   (!supplier. Iscountrynull () &&
   string.compare (supplier. Country, Country)!= (0))
 

Adding this code, the DAL's Update method sends an UPDATE command to the database only in those records that have changed address-related values.

Of course we can also track whether the incoming fields and database data are different, and if not, you don't need to call the DAL's Update method. This method works well when you use direct database commands, because direct database commands do not check Suppliersrow to determine whether a database needs to be invoked.

  Note: Each time the Updatesupplieraddress method is invoked, the database is called once to obtain information about the record that needs to be updated. If the data is modified, the database is called again to update the data. This process can be optimized by creating an overloaded Updatesupplieraddress method that accepts a employeesdatatable that contains all the modifications to the Batchupdate.aspx page. It then calls a database to get all the records in the Suppliers table. Only modified records can be updated in the result set.

Summarize

This chapter learned how to create a fully editable DataList. It allows users to quickly modify the address information for multiple supplier. We first define the editing interface-address,city and country are represented in a textbox-in the ItemTemplate of DataList. Then we added an "Update all" button to the top and bottom of the DataList. After the user has finished modifying, after clicking on one of them, each DataListItem will invoke the Updatesupplieraddress method of the Suppliersbll class.

I wish you a happy programming!

Author Introduction

Scott Mitchell, author of this series of tutorials, 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.