Manipulating data in ASP.net 2.0 36: Editing and deleting Data in DataList overview _ self-study Process

Source: Internet
Author: User
Tags error handling eval exception handling

Introduction

Overview inserting, updating, and deleting data we have learned how to insert, update, and delete data by using controls such as the GridView. The ObjectDataSource and other data controls only need to check the checkbox in the smart tag and do not need to write any code. And DataList does not have these built-in features. We can use the methods in 1.x to implement these functions. As we'll see in this chapter, DataList provides some of the events and attributes to accomplish our purpose, so we need to write some code.

In this chapter we first learn how to create a DataList that supports editing and deleting data. Later in the tutorial we will learn some advanced editing and deletion methods, including validation, Dal and BLL exception handling, and so on.

  Note: Like DataList, Repeater does not provide these built-in features. And there are no DataList of events and attributes in the repeater. So we'll just discuss DataList in this chapter and later chapters.

First step: Create an Edit and delete tutorial page

First create the pages that you need to use this chapter and later chapters. Add a folder named Editdeletedatalist. Then add the following page. Make sure each page contains a site.master.

Default.aspx
Basics.aspx
Batchupdate.aspx
Errorhandling.aspx
UIValidation.aspx
Customizedui.aspx
Optimisticconcurrency.aspx
Confirmationondelete.aspx
Userlevelaccess.aspx


Figure 1: Add page

Like other folders, Default.aspx lists the tutorial chapters. Remember that the Sectionleveltutoriallisting.ascx user control provides this functionality. Drag it from the solution to our page.


Figure 2: Adding the Sectionleveltutoriallisting.ascx user Control

Finally, add these pages to the Web.sitemap. Add the following tag after Master/detail Reports with the DataList and repeater<sitemapnode>:

<sitemapnode title= "Editing and deleting with the DataList" description= "The Samples of Reports, that provide Editing and deleting capabilities "url=" ~/editdeletedatalist/default.aspx "> <sitemapnode title=" Basics "description=" Exam
 Ines the basics of editing and deleting with the DataList control. " Url= "~/editdeletedatalist/basics.aspx"/> <sitemapnode title= "Batch Update" description= "examines how to update m
 Ultiple records at once in a fully-editable DataList. " Url= "~/editdeletedatalist/batchupdate.aspx"/> <sitemapnode title= "Error handling" description= "Learn how to GRA
 Cefully handle exceptions raised during the data modification workflow. " Url= "~/editdeletedatalist/errorhandling.aspx"/> <sitemapnode title= "adding Data Entry Validation" description=
 "Help prevent the data entry errors by providing validation." Url= "~/editdeletedatalist/uivalidation.aspx"/> <sitemapnode title= "Customize" the User Interface "description=" CustomiZe the editing user interfaces. Url= "~/editdeletedatalist/customizedui.aspx"/> <sitemapnode title= "Optimistic Concurrency"
 Learn prevent simultaneous users from overwritting one another s changes. " Url= "~/editdeletedatalist/optimisticconcurrency.aspx"/> <sitemapnode title= "Confirm on Delete" description= "
 Prompt a user for confirmation when deleting a record. " Url= "~/editdeletedatalist/confirmationondelete.aspx"/> <sitemapnode title= "Limit Capabilities Based on User" de
 scription= "Learn to limit" The data modification functionality based on the user s or permissions. " Url= "~/editdeletedatalist/userlevelaccess.aspx"/> </siteMapNode>

After updating the Web.sitemap, browse.


Figure 3: Site Navigation now contains the edit and delete DataList tutorial

Step two: Explore techniques to update and delete data

Using the GridView to edit and delete data is simple because the GridView and ObjectDataSource are very consistent at the bottom. When the Update button is clicked, the GridView automatically assigns the value of the field to the UpdateParameters collection of ObjectDataSource, as discussed in the associated events for inserting, updating, and deleting. The ObjectDataSource Update () method is then fired. We now need to make sure that the appropriate values are assigned to the ObjectDataSource parameters, and then call the update () method. DataList provides the following properties and events to help us accomplish these:

DataKeyField property-Update or delete, we need to uniquely identify each item in DataList. Set this property to the main health of the displayed data. Doing so produces DataList DataKeys collection, each item has a specified DataKeyField.
EditCommand event-When the CommandName property is set to "Edit" button, LinkButton, or ImageButton is fired at the point.
CancelCommand event-When the CommandName property is set to "Cancel" button, LinkButton, or ImageButton is fired at the point.  UpdateCommand event-When the CommandName property is set to "Update" button, LinkButton, or ImageButton is fired at the point. DeleteCommand event-When the CommandName property is set to "Delete" button, LinkButton, or ImageButton is fired at the point.

With the above properties and events, there are four ways to update and delete data:

The technology-datalist using ASP.net 1.x exists prior to ASP.net 2.0 and objectdatasources, and can be edited and deleted directly by programming. This approach requires us to bind data directly to DataList at the BLL level when displaying data or updating deleted records.
Using a separate ObjectDataSource to implement the selection, update and delete the-datalist without the GridView built-in edit deletion does not mean that we cannot add these features. We use ObjectDataSource, as in the case of the GridView, but when you set the ObjectDataSource parameters and call the update () method, you need to create a DataList for the UpdateCommand event   event handler. Using a ObjectDataSource control for selecting but updating and deleting directly against the bll-the use of the second method we need for Updatec Ommand event and parameter assignment, etc. write some code. In fact, we can use ObjectDataSource to implement selecting, update and delete direct call BLL (like the first method). My opinion is that calling BLL directly makes the code more readable. The three methods before using multiple objectdatasources-require some code. If you prefer to stick with as many declarative syntax as possible, the last approach is to use multiple objectdatasources. The first ObjectDataSource gets the data from the BLL and binds to DataList. Add another ObjectDataSource to the update and add it directly to the DataList EditItemTemplate. This is also true for deletions. Three ObjectDataSource bind parameters directly to ObjectDataSource parameters through controlparameters   declaration syntax (instead of UpdateCommand in DataList event handler programmatic processing). This method also requires some coding-we need to call the ObjectDataSource built-in Update () or Delete ()-but the code is much less than the other three methods. The disadvantage of this approach is that multiple   objectdatasources make the page look cluttered.

I like to choose the first method because it provides better scalability, and the design DataList is intended to use this approach. When extended DataList makes it work with the data source control of ASP.net 2.0, it does not have the extensibility or attributes of the "formal" asp.net 2.0 data controls (GridView, DetailsView, and FormView). Of course, other methods are not without merit.

The tutorials on editing and deletion in these chapters use ObjectDataSource to display the data, and then call BLL directly to implement editing and deletion (the third method)

Step three: Add the DataList and configure its ObjectDataSource

In this chapter we will create a DataList to list the product and provide the user with the ability to edit its name and price and remove it. We use ObjectDataSource to display the data and invoke BLL to implement the update and delete functions. First we implement a read-only page that displays the product. Since this functionality has already been implemented in the previous tutorial, we are here soon.

Open the Basics.aspx page under the Editdeletedatalist folder and add a DataList. Then create a ObjectDataSource with a smart tag. Use the GetProducts () method of the Productsbll class in the Select tab to configure it.


Figure 4: Configuring ObjectDataSource with the Productbll class


Figure 5: Select GetProducts ()

Select None in both the Insert,update and delete tabs.


Figure 6: Select (None) in Insert, UPDATE, and Delete tabs

When the configuration is complete, return to the design interface. As we have seen in previous examples, Visual Studio automatically creates ItemTemplate to display the data. Change ItemTemplate to show only the name and price of product. Then set the RepeatColumns to 2.

  Note: As discussed earlier, when modifying data using ObjectDataSource, we need to remove oldvaluesparameterformatstring (or reset to the default value, {0}) in the declaration tag. This chapter ObjectDataSource only to get the data, so there's no need to do that (of course it doesn't matter). when you're done, your page code should look similar to the following:

<asp:datalist id= "DataList1" runat= "Server" datakeyfield= "ProductID" datasourceid= "ObjectDataSource1"
 repeatcolumns= "2" >
 <ItemTemplate>
  
 

Browse the page. Figure 7,datalist Displays the name and price of product in two columns.


Figure 7:datalist shows the Names and prices of the products

  Note: DataList there are some attributes that need to be edited and deleted, and these values are in view state. So when you create a DataList that supports editing and deletion, DataList view state needs to be turned on.

Smart readers should remember view state is disabled when creating editable gridview,detailsviews and Formviews. This is because the ASP.net 2.0 control contains the controls state, which is contiguous when postback.

The view state has been disabled in the GridView only to ignore irrelevant status information, but it maintains control state (which contains the status of edit and delete needs). The DataList was created in the ASP.net 1.x era and did not use control state, so view state must be turned on. The purpose of the control state and the difference between the view state and the control state vs. view state

Step Fourth: Add an editing interface

The GridView control is made up of a collection of fields (BoundFields, Checkboxfields, Templatefields, and so on). These fields can adjust the tag according to the pattern. For example, in read-only mode, BoundField displays the field value as text, and in edit mode it appears as a TextBox, and the Text property of the textbox is assigned the value of the field.

On the other hand, DataList uses template to show its item. Read-only item is displayed with ItemTemplate. When in edit mode, item is displayed with EditItemTemplate. Now there is only one ItemTemplate in our DataList. We need to add a edititemtemplate to support the editing function. In this chapter we use a TextBox to edit the name and price of product. You can create edititemtemplate by declaring a language or Design view (the Edittemplate option for DataList smart Tags).


Figure 8: Selecting EditItemTemplate


Then enter "Product Name:" and "Price:" and drag two more textbox to EditItemTemplate. Set the ID property of the textbox to ProductName and UnitPrice.


Figure 9: Adding a TextBox


We need to bind the fields of product to the associated textbox. Click Edit DataBindings on the Smart tab of the TextBox, and then associate the Text property with the appropriate field. See Figure 10.

  Note: When you bind a UnitPrice to a textbox, you can use ({0:C}) to format it as a currency value, or as a normal number ({0:n}), or unformatted.


Figure 10: Bound field to textboxes


  Note: The Edit DataBindings dialog box in Figure 10 does not contain a checkbox for "bidirectional data binding", and in the edit GridView or DetailsView TemplateField, Or in the template in FormView, there is this checkbox. bidirectional data binding allows the value of the input control to be automatically assigned to the InsertParameters or updateparameters of the associated ObjectDataSource when data is inserted or updated. DataList does not support bidirectional binding-we will see later that when the user makes a change and prepares to update the data, we need to programmatically pass the value of the textbox's text to the UpdateProduct method of the Productsbll class.


Finally, we add the update and Cancel buttons to the EditItemTemplate. As seen earlier, when the Button,linkbutton or ImageButton in the CommandName Repeater or DataList is clicked, Repeater or DataList ItemCommand events are fired. For DataList, if the CommandName is set to a value, another event is fired, as follows:


"Cancel"-Excite CancelCommand Event
"Edit"-Fire EditCommand Event
"Update"-to inspire UpdateCommand event

Remember that these events are fired except for the ItemCommand.

Add two button for EditItemTemplate, one commandname set to "Update" and one set to "Cancel". When you're done, the design interface should look similar to the following:


Figure 11: Add the Update and Cancel buttons for EditItemTemplate

Your markup language should look similar to the following:

 <asp:datalist id= "DataList1" runat= "Server" datakeyfield= "ProductID" datasourceid= " ObjectDataSource1 "repeatcolumns=" 2 "> <ItemTemplate> 

Step Fifth: Add an entry into edit mode

Now we have an editing interface for our DataList. However, there is no way to show that users need to edit product information. We need to add an Edit button for each product, and when clicked, display the DataList item as edit mode. The same can be added through the designer or by directly declaring the code. Make sure the CommandName property of the Edit button is set to ' edit '. After adding, browse the page.


Figure 12: Add edit Buttons

Clicking the button causes postback, but does not enter the product edit mode. To accomplish this, we need to:

Set the EditItemIndex property of the DataList to the index of the DataListItem that was clicked on the Edit button.
rebind data to DataList. When DataList, the DataListItem associated with DataList's EditItemIndex will show EditItemTemplate.

Because the DataList EditCommand event is fired at the point Edit button, the following code is used to create a EditCommand event handler:

protected void Datalist1_editcommand (object source, DataListCommandEventArgs e)
{
Set the DataList ' s EditItemIndex property to the
Index of the DataListItem that is clicked
Datalist1.edititemindex = E.item.itemindex;
Rebind the data to the DataList
Datalist1.databind ();
}

The second parameter type of EditCommand event handler is DataListCommandEventArgs, which is clicked edit The DataListItem Reference (e.item) of the button. First set the EditItemIndex of the DataList to DataListItem for the itemindex you want to edit, and then rebind the data. When you are finished, browse the page again. Click the Edit button, and now the product becomes editable. See Figure 13.


Figure 13: The dot edit Button enables product to be edited

Step Sixth: Save the user's changes

Now dot product's update or Cancel button will have no response. To accomplish the goal we need to create an event handler for DataList's UpdateCommand and CancelCommand. First, you create the CancelCommand event handler, which executes when the Cancel button clicks on the product, allowing the DataList to return to the state before the edit. To enable DataList to show the item in read-only mode, we need:

Setting the DataList EditItemIndex property to a nonexistent DataListItem index-1 is a good choice. (because DataListItem index starts at 0) rebind the data to DataList. Because there is no EditItemIndex association between the DataListItem ItemIndex and DataList, the entire DataList is presented as read-only mode. These can be done through the following code:

protected void Datalist1_cancelcommand (object source, DataListCommandEventArgs e)
{
 //Set the DataList ' s EditItemIndex Property to-1
 datalist1.edititemindex =-1;
 Rebind the data to the DataList
 datalist1.databind ();
}

Clicking the Cancel button now returns to the state before the DataList edit.

Finally we're going to finish UpdateCommand event handler and we need to:

Program gets user input of product name and price, as well as ProductID.
Call the appropriate UpdateProduct overload method in the Productsbll class.
Sets the EditItemIndex property of the DataList to a Non-existent DataListItem index. -1 is a good choice.
Re-help the top data.

The first and second steps are responsible for saving user changes. The third step returns to the state before the DataList edit (same as CancelCommand event handler).

We need to use the FindControl method to get the name and price of product (including, of course, ProductID). When ObjectDataSource is initially bound to DataList, Visual Studio assigns the DataKeyField property of DataList to the primary key value (ProductID) of the data source. This value can be obtained by DataList's DataKey collection. Take some time to verify that DataKeyField is set to ProductID.

The following code completes the above function:

 protected void Datalist1_updatecommand (object source, DataListCommandEventArgs e) {//Read
 In the ProductID from the DataKeys collection int ProductID = Convert.ToInt32 (Datalist1.datakeys[e.item.itemindex]);
 Read in the product name and price values TextBox productName = (TextBox) e.item.findcontrol ("ProductName");
 TextBox UnitPrice = (textbox) E.item.findcontrol ("UnitPrice");
 string productnamevalue = null; if (ProductName.Text.Trim ().
 Length > 0) productnamevalue = ProductName.Text.Trim (); Decimal?
 Unitpricevalue = null; if (UnitPrice.Text.Trim ().
 Length > 0) unitpricevalue = Decimal.Parse (UnitPrice.Text.Trim (), System.Globalization.NumberStyles.Currency);
 Call the Productsbll ' s updateproduct ...
 PRODUCTSBLL Productsapi = new PRODUCTSBLL ();
 Productsapi.updateproduct (Productnamevalue, Unitpricevalue, ProductID);
 Revert the pre-editing state datalist1.edititemindex =-1;
Datalist1.databind (); }

First read the ProductID of the product from the DataKeys collection. Then save the Text property of the two textbox. We use the Decimal.Parse () method to read the value of the UnitPrice textbox so that it can be converted correctly when the value has a currency symbol.

  Note: The Productnamevalue and Unitpricevalue variables are assigned only if the textbox's text specifies a value. Otherwise, a null value is used when the data is updated. that is, our code converts an empty string to a null value, whereas NULL is the default value in the editing interface of the Gridview,detailsview and FormView controls. When the value is obtained, the UpdateProduct method of the Productsbll class is invoked, and the Name,price and ProductID of the product are passed in. Use the same logic as in the CancelCommand event handler to return to the DataList edit state. After the Editcommand,cancelcommand and UpdateCommand event handler are completed, the user can edit the name and price of product. See Figure 14.


Figure 14: All products are read-only when browsing the page


Figure 15: Click Edit Button


Figure 16: After changing the value, click Update to return read-only mode

Seventh Step: Add Delete function

The steps to add the deletion function are almost as much as the editing function. In short, we need to add a Delete button to the ItemTemplate, when clicked:

Reads the associated PROUDCT ProductID from the DataKeys collection.
Call the Deleteproduct method of PRODUCTSBLL class to perform the delete operation.
rebind data to DataList.
First, add a Delete button.

When you click a button commandname "edit", "Update", or "Cancel", the DataList ItemCommand event and another event are fired (for example, when you use "edit" EditCommand Event will be fired). Similarly, when CommandName is "Delete", the DeleteCommand event is fired (along with ItemCommand).

Add a Delete button after the Edit button to set the CommandName property to "delete". When you are done, declare your code as follows:

<ItemTemplate>
 

Although we have added basic editing and deletion capabilities for DataList, it still lacks some advanced features. For example, there is no input field validation-if the user enters price too "expensive", Decimal.Parse throws an exception when converting to Decimal. Similarly, if there is an exception in the BLL or DAL when the data is updated, the user will see a system error. There is no confirmation at the time of deletion and it is likely that the data will be mistakenly deleted. In the following tutorial we will learn how to improve these problems.

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.