In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail the example analysis of insert, update and delete related events in ASP.NET 2.0. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Introduction
When using the built-in GridView, DetailsView, or FormView controls to insert, edit, or delete features, multiple steps occur in the process of adding a new record or updating / deleting a current record. As we discussed in the previous section, when editing a row in GridView, the Update and Cancel buttons replace the edit (Edit) button, and the bound column is converted to TextBox. After the user updates the data and clicks the Save button, the following steps are performed on postback:
1. The GridView control assembles its ObjectDataSource UpdateParameters parameter based on the unique identification field of the current edit row (through the DataKeyNames property), along with the value entered by the user
two。 The GridView control calls its ObjectDataSource's Update () method, which in turn calls the appropriate method of the potential object (ProductsDAL.UpdateProduct, in the previous section).
3. Now, the implicit data, including the saved changes, is rebound to the GridView control
In this series of steps, many events are triggered, which allows us to create event handlers to add custom logic where needed. For example, before step 1, the event that triggers the GridView. Here, if there are any validation errors, we can cancel the update request. When the Update () method is called, the Updating event of ObjectDataSource is triggered, providing an opportunity to increase or customize the value of UpdateParameters. The Updated event of the ObjectDataSource is triggered after the methods of the potential object of the ObjectDataSource are fully executed. The event handler for the Updated event can check the details of the update operation, such as how many rows of data were affected, or whether an exception was thrown. Finally, after step 2, the RowUpdated event for GridView fires; the event handler for this event can check for additional information about the update operation that has just completed.
Figure 1 depicts this series of consecutive events and steps when using GridView updates. The event pattern in figure 1 is not just an update operation in GridView. This series of pre-level and post-level events occur in both the data Web server control and the ObjectDataSource when data is inserted, updated, or deleted from GridView, DetailsView, or FormView.
Figure 1: when data is updated in GridView, a series of Pre- and Post- events are triggered
In this section, we will explore the use of these events to extend the built-in insert, update, and delete capabilities of ASP.NET data Web server controls. We will also look at how to customize the editing interface to update only some of the product fields.
Step 1: update the ProductName and UnitPrice fields of the product
In the editing interface of the previous section, all the fields of the product are included and none of them are read-only. If we strip out a column (QuantityPerUnit) from GridView, the data Web server control will not set the value of ObjectDataSource's QuantityPerUnit UpdateParameters when it is updated. ObjectDataSource passes a null value to the business logic layer method UpdateProduct, which changes the QuantityPerUnit field of the currently edited database record to a value. Similarly, if it is a required field, such as ProductName, if it is removed from the editing interface, the update will fail with a "Column 'ProductName' does not allow nulls" exception. The reason for this is that ObjectDataSource is configured to call the UpdateProduct method of the ProductsBLL class, which expects each product field to correspond to an input parameter. Therefore, the UpdateParameters collection of ObjectDataSource contains each input parameter of the method.
If we want to provide a data Web server control that allows the end user to update only part of the field, we need to programmatically set the missing UpdateParameters value in the ObjectDataSource Updating event handler, or create and call a BLL method for the expected part of the field. Let's discuss it in the next steps.
In particular, let's create a page that displays only the ProductName and UnitPrice fields in an editable GridView. The GridView editing interface will only allow the user to update the two displayed fields, ProductName and UnitPrice. Because this editing interface provides only part of the fields of the product, we need to create an ObjectDataSource that uses the existing UpdateProduct method of BLL and programmatically sets the value of the missing fields of the product in the Updating event handler, or we need to create a new BLL method that accepts only some of the fields that have been defined in GridView. In this section, we use the latter to create an overload of the UpdateProduct method, which extracts three input parameters: productName, unitPrice, and productID:
[System.ComponentModel.DataObjectMethodAttribute (System.ComponentModel.DataObjectMethodType.Update, false)] public bool UpdateProduct (string productName, decimal? UnitPrice, int productID) {Northwind.ProductsDataTable products = Adapter.GetProductByProductID (productID); if (products.Count = = 0) / / no matching record found, return false return false; Northwind.ProductsRow product = products [0]; product.ProductName = productName; if (unitPrice = = null) product.SetUnitPriceNull (); else product.UnitPrice = unitPrice.Value; / / Update the product record int rowsAffected = Adapter.Update (product); / / Return true if precisely one row was updated, otherwise false return rowsAffected = = 1;}
Similar to the original UpdateProduct method, this overloaded method first checks to see if a product with a specified ProductID exists in the database. If it does not exist, it returns false, indicating that the request to update product information failed. Otherwise, it updates the ProductName and UnitPrice fields of the existing product record and submits the update by calling the Update () method of TableAdapter, passing it into the ProductsRow instance.
With this extra processing of our ProductsBLL class, we can now create a simple GridView interface. Open DataModificationEvents.aspx in the EditInsertDelete folder and add a GridView control to the page. Create a new ObjectDataSource and configure it to use the ProductsBLL class, its Select () method maps to GetProducts, and the Update () method maps to UpdateProduct method overloads that accept only productName, unitPrice, and productID input parameters. Figure 2 shows the data source configuration wizard when mapping the Update () method of ObjectDataSource to the new UpdateProduct method of the ProductsBLL class.
Figure 2: mapping the Update () method of ObjectDataSource to the new UpdateProduct overload
Because our example will only require the ability to edit data, without inserting or deleting records, take some time to make it clear that the Insert () and Delete () methods of the ObjectDataSource will not map to any methods of the ProductsBLL class-- by going to the tab pages of INSERT and DELETE and selecting from the drop-down list (none).
Figure 3: on the Tab page of INSERT and DELETE, select from the drop-down list (none)
After completing this wizard, check enable Editing from the functional tag of GridView.
After completing the data source configuration wizard and binding to GridView, Visual Staudio has added their declaration syntax. Go to the source view to see the declaration tag of the ObjectDataSource, which will look like this:
[System.ComponentModel.DataObjectMethodAttribute (System.ComponentModel.DataObjectMethodType.Update, false)] public bool UpdateProduct (string productName, decimal? UnitPrice, int productID) {Northwind.ProductsDataTable products = Adapter.GetProductByProductID (productID); if (products.Count = = 0) / / no matching record found, return false return false; Northwind.ProductsRow product = products [0]; product.ProductName = productName; if (unitPrice = = null) product.SetUnitPriceNull (); else product.UnitPrice = unitPrice.Value; / / Update the product record int rowsAffected = Adapter.Update (product); / / Return true if precisely one row was updated, otherwise false return rowsAffected = = 1;}
Because the Insert () and Delete () methods of ObjectDataSource have no mapping, there are no InsertParameters or DeleteParameters fragments. In addition, because the method maps to the UpdateProduct method overload, it accepts only three input parameters, and the UpdateParameters fragment contains only three Parameter instances.
Notice that the property of ObjectDataSource is set to original_ {0}. This property is automatically set by Visual Studio when using the data source configuration wizard. Therefore, since our BLL method does not need to pass in the original Productid value, remove all these property settings from the declaration syntax of ObjectDataSource.
Note: If you if you simply clear the value of the OldValuesParameterFormatString property from the property window in Design view, this property will still exist in the declaration syntax, but will be set to an empty string. Either delete the attribute from the declaration syntax, or from the properties window, set its value to the default value: {0}.
Although ObjectDataSource contains only UpdateParameters,Visual Studio for productName, unitPrice, and productID, add a bound column or CheckBoxField for each field of the product.
Figure 4: GridView contains a BoundField or CheckBoxField for each field of the product
When the end user edits a product and clicks its save button (Update), the GridView iterates through the editable fields and assigns the values entered by the user to the corresponding parameters in the UpdateParameters collection of the ObjectDataSource. If there is no corresponding parameter, GridView adds one to the parameter collection. Therefore, if our GridView contains bound or CheckBox columns for all fields of the corresponding product, then ObjectDataSource will call a method overload that accepts these parameters, regardless of the fact that the ObjectDataSource declaration tag specifies that only three input parameters are accepted (see figure 5). Similarly, if there are some combinations of GridView non-read-only columns, and none of the UpdateProduct overloads can accept the corresponding parameters, an exception is thrown when an attempt is made to save.
Figure 5: GridView will add parameters to ObjectDataSource's UpdateParameters collection
To ensure that ObjectDataSource calls UpdateProduct overloads that only accept productName, unitPrice, and productID parameters, we need to limit GridView to only two editable columns, ProductName and UnitPrice. This can be achieved by removing other bound columns and CheckBox columns, or by setting the ReadOnly property of these columns to true, or by using a combination of these two methods. In this section, let's simply delete all columns of GridView except the ProductName and UnitPrice binding columns, and then the declaration tag for GridView will look like this:
Even if we overload the expected 3 input parameters, there are only two bound columns in our GridView. This is because the productID input parameter is the value of a primary key (primary key), which is passed in through the DataKeyNames property of the current edit row.
Our GridView control, along with this UpdateProduct overload, allows a user to edit only the product name and unit price without losing other product fields.
Figure 6: interface that only allows editing of ProductName and UnitPrice
Perfect UnitPrice formatting
Although the GridView instance shown in figure 6 works properly, the UnitPrice field has not been formatted at all, resulting in a lack of currency symbols when displaying prices and four decimal places. To apply currency formatting to non-edited rows, simply set the DataFormatString property of the UnitPrice bound column to {0HtmlEncode c} and its HtmlEncode property to false.
Figure 7: setting the DataFormatString and HtmlEncode properties of the UnitPrice bound column
With this change, the non-edited line formats the price into currency; however, the currently edited line still appears without a currency symbol and retains four decimal places.
Figure 8: non-edited lines are now formatted to currency values
By setting the ApplyFormatInEditMode property of this bound column to true (the default is false), you can apply the formatting instructions specified in the DataFormatString property to the editing interface.
Figure 9: set the ApplyFormatInEditMode property of this bound column to true
With this change, the UnitPree value displayed in the current edit line is also formatted as currency.
Figure 10: the value of the current edit line is now also formatted as currency
However, if you update the product price to a value with a currency symbol in the text box-for example, $19.00-a FormatException exception will be thrown. When GridView attempts to assign a user-supplied value to the UpdateParameters collection of ObjectDataSource, it cannot convert the UnitPrice string "$19.00" to the decimal type required by the parameter (see figure 11). To remedy this problem, we can add an event handler to the RowUpdating event of GridView and have it format the UnitPrice entered by the user into decimal in currency format.
The second parameter accepted by the RowUpdating event of this GridView is an object of type GridViewUpdateEventArgs, which contains a NewValues dictionary in which each attribute holds the value entered by the user, ready to be assigned to the UpdateParameters collection of the ObjectDataSource. We can rewrite the UnitPrice value in the existing NewValues collection to a currency amount, which is resolved by the code in the following event handler:
Protected void GridView1_RowUpdating (object sender, GridViewUpdateEventArgs e) {if (e.NewValues ["UnitPrice"]! = null) e.NewValues ["UnitPrice"] = decimal.Parse (e.NewValues ["UnitPrice"] .ToString (), System.Globalization.NumberStyles.Currency);}
If the user provides a UnitPrice value such as "$19.00", this value is calculated by Decimal.Parse and parsed into a currency amount value rewrite. This correctly parses currency values, whether they are currency symbols, commas, decimal points, and so on, and uses the NumberStyles enumeration of the System.Globalization namespace.
Figure 11 shows the problem caused by the currency symbol in the UnitPree value entered by the user, and shows how to parse such input correctly using GridView's RowUpdating event handler.
Figure 11: the UnitPree value of the current edit line is now formatted as a monetary amount
Step 2: stop NULL UnitPrices
Although the database is configured to allow the UnitPrice field in the Products table to be null, we may want to prevent users from accessing this particular page and specify an empty UnitPrice value. More specifically, if the user forgets to enter a UnitPrice value when editing a product line record, instead of saving the result to the database, we might as well display a prompt message to the user, from beginning to end of this page, any editors to the product must specify a price.
The GridViewUpdateEventArgs object of the event handler passed to GridView contains a Cancel property, which, if set to true, aborts the update process. Let's extend the RowUpdating event handler, set e.Cancel to true and display a message explaining why the UnitPrice value in the NewValues collection is null.
First, add a Label server control to the page and name it MustProvideUnitPriceMessage. This Label control will show whether the user forgot to specify a UnitPree value when updating a product. Set the Text property of this Label to "you must provide a price for the product." . I have also added a new CSS category called Warning to the Styles.css file, defined as follows:
.warning {color: Red; font-style: italic; font-weight: bold; font-size: XMurray;}
Finally, set the CssClass property of Label to Warning. The designer will display the red, italic, bold, and larger font warning message above the GridView.
Figure 12: a Label control has been added above the GridView
If the Label control is hidden by default, set its Visible property to false in the Page_Load event handler.
Protected void Page_Load (object sender, EventArgs e) {MustProvideUnitPriceMessage.Visible = false;}
If the user tries to update a product without specifying a UnitPree value, we want to cancel the update and display a warning label. Add the following code to GridView's RowUpdating event handler:
Protected void GridView1_RowUpdating (object sender, GridViewUpdateEventArgs e) {if (e.NewValues ["UnitPrice"]! = null) {e.NewValues ["UnitPrice"] = decimal.Parse (e.NewValues ["UnitPrice"] .ToString (), System.Globalization.NumberStyles.Currency);} else {/ / Show the Label MustProvideUnitPriceMessage.Visible = true; / / Cancel the update e.Cancel = true;}}
If a user tries to save a product without specifying a price, the update is canceled and a useful prompt is displayed. Although the database (and business logic) allows UnitPrice with null values, it is not allowed for this particular ASP.NET page.
Figure 13: users cannot leave UnitPrice empty
So far we have seen how to use the RowUpdating event of GridView to programmatically change the parameter values assigned to the UpdateParameters collection of ObjectDataSource, and how to cancel the update process altogether. These ideas can also be extended to DetailsView and FormView controls and applied to inserts or deletes.
These tasks can also be done at the ObjectDataSource layer through the Inserting, Updating, and Deleting event handlers. These events are triggered before the associated method of the implied object is called and provide a last chance to change the set of input parameters or cancel the operation altogether. The event handler corresponding to these three events passes in an object of type ObjectDataSourceMethodEventArgs, and we are interested in these two properties:
Cancel, which cancels the operation in progress if it is set to true
InputParameters, which is a collection of InsertParameters, UpdateParameters, or DeleteParameters, depending on whether this is an event handler for Inserting, Updating, or Deleting events
To illustrate how parameter values are handled at the ObjectDataSource level, let's include a DeailsView in the page that allows the user to add a new product record. This DetailsView will be used to provide a quick way to add a new product record to the database. In order to keep the interface consistent when adding new products, we only allow users to enter ProductName and UnitPrice fields. As default values, these values provided in the DetailsView insert interface will be set to the null value of a database. However, we can use ObjectDataSource's Inserting event to inject different default values, as we'll see in a moment.
Step 3: provide an interface to add new products
Above the GridView, drag and drop a DetailsView control from the toolbox to the designer, empty its Height and Width properties, and bind it to an existing ObjectDataSource on the page. This will add a bound column or CheckBox column for each field of the product. Because we want to use this DetailsView control to add new products, we need to check enable insert from its functional tag; however, there is no such item, because the Insert () method of this ObjectDataSource has not yet been mapped to the method of the ProductsBLL class (recall that we set this mapping to (none) when configuring the data source-see figure 3).
To configure the ObjectDataSource again, select the link to configure data sources from its functional tag and load the wizard. The first screen allows you to change the implicit object that ObjectDataSource binds to; let it remain ProductsBLL. The next screen lists the mapping of methods from ObjectDataSource to implicit objects. Although we have explicitly specified that Insert () and Delete () do not map to any methods, if you go to the tab pages of INSERT and DELETE, you will still see a mapping there. This is because ProductsBLL's AddProduct and DeleteProduct methods use DataObjectMethodAttribute to indicate that they are the default methods for serving Insert () and Delete (), respectively. Therefore, the ObjectDataSource wizard automatically selects them each time it runs, unless a different value is explicitly specified there.
Leave the Insert () method still pointing to the AddProduct method, but again select (none) from the drop-down list on the tab page of DELETE.
Figure 14: select the AddProduct method from the drop-down list on the Tab page of INSERT
Figure 15: select from the drop-down list on the Tab page of DELETE (none)
After these changes are made, an InsertParameters collection is included in the declaration syntax of the ObjectDataSource, as follows:
Running the wizard again causes the OldValuesParameterFormatString property to be re-added. Set this property to the default value ({0}) or remove them completely from the declaration syntax.
With ObjectDataSource providing the ability to insert data, the functional tag of DetailsView now contains the "enable insert" checkbox; back to the designer and check this item. Then, reduce the column straightness of DetailsView, which contains only two bound columns-ProductName and UnitPrice, as well as a CommandField. At this point, the declaration syntax for DetailsView will be as follows:
Figure 16 shows the page viewed through the browser at this time. As you can see, DetailsView lists the name and price of the first product (Chai). However, what we need is an plug-in interface to provide a means for users to quickly add a new product to the database.
Figure 16: the DetailsView is currently rendered in read-only mode
To show the DetailsView of insert mode, we need to set the DefaultMode property to Inserting. This allows DetailsView to appear in insert mode after accessing and inserting a new record for the first time. As shown in figure 17, such a DetailsView provides a quick interface for adding new records.
Figure 17: this DetailsView provides an interface to quickly add new products
When the user enters a product name and price (such as "Acme Wate" and 1.99, as shown in figure 17) and clicks the insert button, a postback occurs and the insert workflow begins until a new product record is finally added to the database. DetailsView maintains its insert interface, and GridView automatically reproduces the data sources bound to it in order to include newly added products, as shown in figure 18.
Figure 18: product "Acme Water" has been added to the database
Although not shown in the GridView in figure 18, the missing product fields in the DetailsView interface-CategoryID, SupplierID, QuantityPerUnit, and so on-are assigned a database null value. You can see this by performing the following steps:
1. Server Explorer to Visual Studio
two。 Expand the NORTHWND.MDF database node
3. Right-click on the power saving in the Products data sheet
4. Select Show Table data
This lists all records in the Products table. As shown in figure 19, except for the ProductID, ProductName, and UnitPrice fields, the other fields for our new product are null values.
Figure 19: other fields of products not provided in DetailsView are assigned null values
We may want to give one or more of these fields a default value instead of NULL, either because NULL is not the best default, or because the database field itself does not allow null values. To achieve this, we can programmatically set the parameter values in the InputParameters collection of these DetailsView. This can be done in DetailsView's ItemInserting event handler or in ObjectDataSource's Inserting event handler. Since we've seen how to use pre- and post-level events in data Web server controls, let's explore ObjectDataSource events this time.
Step 4: assign values to the CategoryID and SupplierID parameters
Here we assume that when our application adds a new product through this interface, the CategoryID and SupplierID fields should be assigned a value of 1. As mentioned earlier, the ObjectDataSource control has a pair of events for pre- and post-level that occur during data changes. When its Insert () method is called, ObjectDataSource first triggers its Inserting event, then calls the business method to which its Insert () method is mapped, and finally triggers the Inserted event. This Inserting event handler gives us a last chance to process the input parameters or cancel the operation altogether.
Note: in a real application, you probably want the user to specify both category and supplier values, and to choose this value based on certain criteria and business logic (instead of blindly choosing ID as 1). In any case, this example illustrates how to programmatically set the value of an input parameter in the event of ObjectDataSource's pre-level.
Take the time to create an event handler for the Inserting event of ObjectDataSource. Notice that the second input parameter to the event handler is an object of type ObjectDataSourceMethodEventArgs, which has a property to access the parameter collection (InputParameters) and a property to cancel the operation (Cancel).
Protected void ObjectDataSource1_Inserting (object sender, ObjectDataSourceMethodEventArgs e) {}
At this point, the InputParameters property contains the InsertParameters collection assigned to the ObjectDataSource through DetailsView. To modify one of these parameters, simply use: e.InputParameters ["paramName"] = value. So, to set CategoryID and SupplierID to 1, adjust the Inserting event handler to the following:
Protected void ObjectDataSource1_Inserting (object sender, ObjectDataSourceMethodEventArgs e) {e.InputParameters ["CategoryID"] = 1; e.InputParameters ["SupplierID"] = 1;}
This time when we add a new product (such as Acme Soda), the CategoryID and SupplierID fields of the new product are assigned to 1 (see figure 20).
Figure 20: the CategoryID and SupplierID fields for the new product are now set to 1
This is the end of the article on "sample analysis of insert, update and delete related events in ASP.NET 2.0". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.