Manipulating data 38 in asp.net 2.0: Handling Exceptions to BLL and dal _ self-study process

Source: Internet
Author: User
Tags eval exception handling visual studio

Introduction

In the DataList Edit and delete Data overview, we create a DataList that provides simple editing and deletion capabilities. While the functionality is complete, it is unfriendly to the user. Because all exceptions generated during the edit and delete process are not processed. For example, if you omit the name of the input product, or when you edit the product by typing "Very affordable!" in price, you throw an exception. Because these exceptions are not caught in the code, the page displays a detailed error message for the ASP.net runtime.

As we see in the Bll/dal layer exception in the ASP.net page, if an exception occurs in BLL or DAL, detailed information is returned to ObjectDataSource and then to the GridView. We have learned how to handle these exceptions gracefully: Create updated or rowupdated event handling for ObjectDataSource or GridView, check for exceptions, and then indicate that the exception is handled.

However, when using DataList, we did not update and delete data through ObjectDataSource. We are directly through the BLL to achieve. In order to detect an exception to the BLL or DAL, we need to write exception handling code in the ASP.net page. In this chapter, we will learn how to handle exceptions skillfully when using DataList editing.

  Note: In the DataList Edit and delete Data overview, we discuss several different ways to edit and delete data, some of which involve using ObjectDataSource to edit and delete. If you use these techniques, you can handle these anomalies directly through ObjectDataSource updated or deleted event processing.

The first step: Create an editable DataList

First, create an editable DataList. Open the Errorhandling.aspx page under the Editdeletedatalist folder, add a DataList with the ID products and a objectdatasouce named Productsdatasource. Select the GetProducts () method of the Productsbll class under the Select tab. Select None in the Insert,update and delete tabs.


Figure 1: Configuring ObjectDataSource

When you finish objectdatasouce, Visual Studio automatically creates a ItemTemplate. Replace it with a ItemTemplate that displays the name and price of each product and contains an edit button, and then create a textbox to display name and price and include an Update button and cancel The EditItemTemplate of the button. Finally, set the DataList RepeatColumns property to 2.

After you have done this, your declaration code should be similar to the following. Check and ensure that the CommandName properties of the Edit,cancel and Update button are set to "Edit", "Cancel", and "Update" respectively.

<asp:datalist id= "Products" runat= "server" datakeyfield= "ProductID" datasourceid= "Productsdatasource" repeatcolumns= "2" > <ItemTemplate>  

  Note: The DataList view state must be open in this chapter. Look at the page, see Figure 2.


Figure 2: Each product contains an edit Button

Now the Edit button just causes a postback-to not make the product editable. To achieve the editing function, we need to create event handling for Editcommand,cancelcommand and UpdateCommand. The EditCommand and CancelCommand events only need to update the EditItemIndex properties of the DataList and rebind the data to DataList.

protected void Products_editcommand (object source, DataListCommandEventArgs e)
{
 //Set the DataList ' s EditItemIndex to the
 //index of the DataListItem this was clicked
 Products.edititemindex = E.item.itemin Dex;
 Rebind the data to the DataList
 products.databind ();
}
protected void Products_cancelcommand (object source, DataListCommandEventArgs e)
{
 //Set the DataList ' s EditItemIndex Property to-1
 products.edititemindex =-1;
 Rebind the data to the DataList
 products.databind ();
}

UpdateCommand event handling is a little bit cumbersome. It needs to read the edited product's ProductID from the DataKey collection, and the name and price of the product in the textbox in EditItemTemplate, It then calls the UpdateProduct method of the Productsbll class, and finally returns to the state before the DataList edit.

Here we use the UpdateCommand event handling code in the overview of editing and deleting data in DataList.

 protected void Products_updatecommand (object source, DataListCommandEventArgs e) {//Read I
 n the ProductID from the DataKeys collection int ProductID = Convert.ToInt32 (Products.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 products.edititemindex =-1;
Products.databind (); }

When there is an illegal input-it may be an incorrect price format, such as "-$5.00", or ignoring the product's name-can cause an exception. A asp.net run-time error appears on the page because the UpdateCommand event processing has not handled the exception. See Figure 3.


Figure 3: When an unhandled exception occurs, the user will see this error page

Step two: Handling Exceptions in UpdateCommand Event handler

In the update process, exceptions can occur in UpdateCommand event handling, or in BLL or DAL. For example, if a user enters a "too expensive" price, the Decimal.Parse in UpdateCommand event handling throws FormatException exceptions. If the user ignores the name of product or the price is a negative number, the Dal throws an exception.

When an exception occurs, we want to display our own defined information. Add a Label control with ID exceptiondetails to the page and set the text to a red, oversize, bold Italian font by setting the CssClass property to the warning CSS class. This class is defined in the Styles.css file.

When an exception occurs, we only want this label to appear once. In other words, the label's warning message needs to be hidden when the postback is behind. This can be done either by clearing the label's Text property or by setting the Visible property to False (in Page_Load) (as we did in the Bll/dal layer in the ASP.net page) or by disabling the label's view state. We use the latter method here.

<asp:label id= "Exceptiondetails" enableviewstate= "False" cssclass= "Warning" runat= "
 server"/>

When an exception occurs, we display the exception's information on the label's Text property. Because view state is disabled and then postback, the Text property is automatically lost, back to the default (empty string), which hides the warning message.

When an exception occurs, the information is displayed on the page, and we need to add a try in UpdateCommand event handling .... A catch block. The try section contains code that may throw an exception, and the Catch section contains code that needs to be executed when an exception occurs. More Try ... Catch block information reference exception handling fundamentals.

protected void Products_updatecommand (object source, DataListCommandEventArgs e)
{
 //Handle any exceptions Raised during the editing process
 try
 {
  //Read in the ProductID from DataKeys collection
  int producti D = Convert.ToInt32 (Products.datakeys[e.item.itemindex]);
  ... Some code omitted for brevity ...
 }
 catch (Exception ex)
 {
  //Todo:display information about the Exception in Exceptiondetails
 }
}

No matter what type of exception is thrown in a try block, the code for the Catch block executes. The type that throws the exception-dbexception, nonullallowedexception, ArgumentException, etc.-depends on the first error. If it is a database-level issue, a dbexception is thrown. If it is UnitPrice, UnitsInStock, UnitsOnOrder, or ReorderLevel field has an illegal value, it throws ArgumentException (We've added code to validate field values in productsdatatable, see Creating a business Logic layer)

We can provide better help to the user based on the type of exception that is caught. The following code-essentially the same as the exception that handles the Bll/dal layer in the ASP.net page-provides this functionality:

private void Displayexceptiondetails (Exception ex)
{
 //Display a user-friendly
 message Exceptiondetails.text = "There was a problem updating the product."
 If (ex is System.Data.Common.DbException)
  Exceptiondetails.text + = "Our database is currently experiencing problems. Please
   try again later. ";
 else if (ex is nonullallowedexception)
  Exceptiondetails.text = "There are one or more required fields that are
   mi Ssing. ";
 else if (ex is ArgumentException)
 {
  string paramname = ((ArgumentException) ex). paramname;
  Exceptiondetails.text = =
   string. Concat ("The", ParamName, "value is illegal.");
 }
 else if (ex is applicationexception)
  Exceptiondetails.text + = ex. message;
}

Finally, only the Displayexceptiondetails method needs to be invoked.

Complete Try ... After the catch, the user will see more useful error messages, as shown in Figure 4, 5. Note that when an exception occurs, the DataList remains in an editable mode. This is because when an exception occurs, the control flow immediately moves to the catch block, ignoring the code that moves DataList to the edit state.


Figure 4: Error message when a required field is ignored by the user


Figure 5: Error message when entering an illegal price

Summarize

The GridView and ObjectDataSource provide the event handling that contains exception information during the update and deletion process and the properties that indicate whether the exception was handled. The DataList that use BLL directly do not have these characteristics, and we need to deal with these exceptions ourselves.

In this chapter we learned how to add a try in the UpdateCommand during the DataList update ... Catch blocks to handle exceptions. If any exception occurs, the code in the Catch block executes and the error message is displayed on the Exceptiondetails label.

Now, DataList does not prevent the occurrence of anomalies at the first time. Although we know that a negative price value produces an exception, we do not add a feature that prevents users from entering such a value. In the following chapters, we'll learn how to validate user input by adding validation controls in EditItemTemplate to reduce these anomalies.

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.