This topic contains the following sections:
- Introducing SmartBatchUpdate
- Pending Changes Concept
- Rich User Interface
- Streamlined Editing Process
- Built-in Changes Management
- Hierarchical Tables Support
- Automatic Changes Preservation
- Updating to Physical Database
- Localization
- Compatibility with Other Features
- Client-side Programmability
- Server-side Programmability
Introducing SmartBatchUpdate
SmartBatchUpdate is a new feature in WebGrid 7 which enables you to perform multiple edits across multiple tables in real-time without postback/callback. All pending changes will be submitted into server at once with a single AJAX callback, thus eliminates waiting time and improves data editing experience in overall.
When WebGrid is operating in batch update editing mode, you can make multiple edits - such as adding new row, editing row, and deleting row - in real-time without server contact. You can also make multiple edits across hierarchical child tables which are linked through valid referential integrity in the same consistent fashion. |
SmartBatchUpdate also supports more advanced scenarios such as cascading inserts and deletes on hierarchical tables. This allows you to conveniently add new master record and its child records in a row - making data entry across hierarchical tables a snap. Furthermore, WebGrid stores the relation between each new record and intelligently perform new identity translation and mapping it to related child records during physical database updates - freeing developers from tedious and lengthy codes.
SmartBatchUpdate provides numerous benefits for developers and end users, such as:
- Improves data editing experience
Unlike traditional data editing, WebGrid doesn't trigger page postback/callback when a row edit occurred. By eliminating the wait time for each row edits, end users can perform data editing faster and more efficient than ever. - Reduces server workload
SmartBatchUpdate saves the changes of each modified row entirely in client-side which allows WebGrid to efficiently manage all pending changes without have to go back-and-forth to server. When end-users are ready to commit changes, WebGrid will send a single AJAX callback to submit all changes to be processed at the server. That translates to more efficient resource utilization and minimized server workload. - Prevents data entry errors
SmartBatchUpdate includes powerful runtime features to help you make correct changes on data and prevent erroneous changes which you want to avoid at all costs. The Undo Changes feature lets end-users to undo a row changes before it is sent to server for processing. The Review Changes feature enables end-users to review all pending changes in an intuitive dialog box interface, where end-users can make correction on specific changes across multiple tables, or undo the changes.
Pending Changes Concept
SmartBatchUpdate employs pending changes concept to provide solid functionality and architecture for its batch update features. With the concept, every row that has changed since its first load will result in a pending change.
A record row can contain only one pending change at a time, which is one of four modes below:
- Unmodified. When a change is undo'ed, the record will be set back to Unmodified.
- Added. Newly added row will be marked as Added pending change.
- Modified. Edited row will be marked as Modified pending change.
- Deleted. Deleted row will be marked as Deleted pending change.
Each row's pending change is stored based on its corresponding table. This means that each table contains one or more pending changes which are associated with each logical row. As a result, SmartBatchUpdate provides solid and consistent object models and interfaces which enable pending changes to be consumed in multiple tables (hierarchical) configuration. For more information about batch update support for Hierarchical feature, please read Hierarchical Tables Support. |
The following illustration describes the pending changes concept in a hierarchical Grid.
Pending changes are stored locally on client-side and can be accessed programmatically through client-side API.
Furthermore, pending changes are automatically restored and synchronized with the current view whenever the Grid performed a FlyPostBack action - such as sorting, filtering, grouping, etc - or page full postback. This provides users with greater experience to interacting with information while maintaining current changes simultaneously. |
SmartBatchUpdate also includes built-in pending changes management, such as ability to undo changes, accept changes, as well as review changes. For more information about pending changes management, please see Built-in Changes Management.
It's important to note that WebGrid requires your tables to have at least one unique key field, which is assigned to DataKeyField property of each WebGridTable instance. Multiple key fields scenario is also supported.
When Accept Changes command is invoked by users, WebGrid submits all pending changes to server in a single FlyPostBack (AJAX) callback. Upon receiving batch update request, WebGrid will automatically apply all pending changes to the data source in batch. Depending on your data source type, WebGrid will decide whether it should automatically apply the changes to physical database. To learn more about physical database updates, please visit Updating to Physical Database. |
With solid and extensible pending changes architecture provided by SmartBatchUpdate, WebGrid 7 delivers reliable client-side editing solution for your Web application, where data lost is not an option.
Rich User Interface
In addition to solid editing architecture and powerful runtime features, SmartBatchUpdate also provides your end-users with rich visual elements to easily determine added, modified and deleted rows.
The following image shows a WebGrid in hierarchical tables with several pending changes.
Figure 1. WebGrid provides rich visual hints and indicators for pending changes.
SmartBatchUpdate includes additional visual elements and indicators, such as explained below:
- Changes indicator in row header
The visual indicator in row header allows users to quickly distinguish the changes status of each row. Added row is marked with icon; modified row is marked with icon; while deleted row is marked with icon.
- Visual row style
Different row change status will have different row style to let users recognize the status of each change instantly. By default, added rows are marked with light yellow, modified rows with light green, and deleted rows with light red. These visual styles can be customized through AddedRowStyle, ModifiedRowStyle and DeletedRowStyle respectively.
- Pending changes status and related commands in status bar
Whenever users make changes to data, add or remove a row, WebGrid will automatically maintain the pending changes status by updating the related user interface elements in the status bar area. The pending changes status makes it easy for users to understand the current changes state, as well as to perform an action that related to the current
changes such as accepting all changes.
- Integration with context menu
SmartBatchUpdates naturally integrates into existing context menu interface. WebGrid will display various pending changes related command depending on the row state and the settings provided in BatchUpdateSettings object.
- Callout notification on lost focus
Users tend to forget to save changes when they are doing multiple tasks at the same time. With the eye-catching Vista-style notification in WebGrid 7, that is nothing to worry about.
The Vista-style notification will appear automatically when WebGrid lose its focus and pending changes existed.
- Prompt on page navigation
Better yet - users will be prompted when they are about to leave the page while pending changes existed. This feature is especially useful to avoid changes lost due to accidental hyperlink clicks or browser close.
Streamlined Editing Process
SmartBatchUpdate incorporates streamlined editing behaviors to make it even easier, faster and more convenient for users to work with data.
When the batch update feature is enabled, the following behaviors will be automatically enabled:
-
Pending changes merging
A record can contain only one mode of changes. Therefore, if you perform several changes on the same mode, the pending changes will merge automatically. If the change mode is different, it will remove the previous changes and set the latest change mode as active.
For instances, consider the following scenarios:- User edited ContactName on record A. Next, CustomerName and Country are changed. The latter changes will be merged with first changes, resulting in single pending change that contains three fields edit.
- User edited a record then later deletes it. In such case, the previous changes will be undo'ed and the delete pending change is added.
- User added a record then later edits more fields. The record will remain marked as added pending change, while the latter edits will be merged.
- User added a record the later deletes it. In such case, the record will be physically deleted from client view. Its pending change will be removed as well.
- Go to next row on last cell
When you pressed TAB key to edit data and past the last cell of the row, the edited row will be marked as pending changes. The active cell selection will also be set to the next row, which allows users to edit data faster.
- Unique auto-increment fields will be set to (Auto)
WebGrid will automatically set auto-increment column - which is usually used as DataKeyField - as read-only to avoid unnecessary data update error. Furthermore, the auto-increment field will use a user-friendly text such as "Auto" which tells the users that the value of the cell is automatically generated.
- Automatically generate key values for auto-increment fields
WebGrid includes ability to generate key values for auto-increment fields to simulate the database structure in the client side, which enables the pending changes concept to work effectively and reliably.
- Select first cell after adding new row
WebGrid provides a new setting to focus the selection to first editable cell upon successful row adding operation, which significantly improves data entry process. This setting can be turned on by setting SelectFirstCellOnAdd to true in the LayoutSettings object.
- Rows with deleted pending change can't be edited
When a row is marked with deleted pending change, WebGrid disables the row from further editing. This behavior is designated to prevent conflicts and unnecessary errors during the server-side batch update process. - New rows will always be added to the last position in the table
Add pending changes in WebGrid will always be shown consistently in the last position of the table according to the sequence of insertion. This design allows users to easily locate newly added rows whenever they need to access it. Furthermore, the added rows will be displayed regardless of the view settings such as in the condition of sorted, filtered or grouped.
- Added row will be removed from view on delete
When delete action is performed on newly added row, WebGrid intelligently performs undo action on the specified new row. As a result, the added row will be removed from the client view as well as its associated pending changes.
In addition to the editing behaviors enhancement, SmartBatchUpdate also enhances the user experience in overall. To learn more, please see automatic changes preservation and compatibility with existing features. |
Built-in Changes Management
SmartBatchUpdate provides a high-level built-in changes management, in addition to the solid underlying infrastructure which maintains the integrity and consistency of pending changes and batch update process.
Changes management in WebGrid 7 includes the following features:
-
Undo Changes
WebGrid stores all pending changes and all its associated row objects in client side. This design enables WebGrid to track the changes made on each record. Therefore, it allows users to undo a pending change completely.
You can access Undo Changes command by bringing the row's context menu (right click on selected row). If you would like to undo all changes that you have made, you can click on Undo All Changes command in the row's context menu. Alternatively, you can easily locate the command in the status bar.
Please note that undo changes command will revert all changes back into its original state. Thanks to the state-of-the-art pending changes architecture, the operation is done in real-time without the needs for server postback/callback.
-
Review Changes
Designed with solid architecture, SmartBatchUpdate allows your end user to make dozens to hundreds of pending changes in a single session.
For instance, end user is allowed to make changes from one page, navigate to other page through paging function and make changes on the other pages, and so on. With so many changes in different views, users often have difficulty in reviewing or locating the pending changes.
To support these dynamic scenarios, users will need the ability to access all pending changes that they have made in different views. Review Changes is a powerful runtime feature that makes it easy and efficient for users to review all changes regardless of the tables and pending changes state.
Review Changes feature sports sleek dialog box interface to provide end user with a streamlined and convenient access to all pending changes within a single location. See below screenshot to get a better picture.
Review Changes dialog box provides easy-access to all pending changes across tables and views - makes it easy for users to undo several records or accept changes.
Note that the changes will be preserved even though the view has changed completely eg, through sorting or paging. To learn more, see Automatic Changes Preservation mode.
Hierarchical Tables Support
SmartBatchUpdate includes full support for hierarchical tables configuration, makes it the most advanced and reliable solution for enterprise-class data editing requirements.
Consider a WebGrid with Customers-Order-Order Details configuration. Ideally, end user will need the ability to perform changes in child table in the same way and manner as they do it in root table.
WebGrid Enterprise 7's unique SmartBatchUpdate technology simply makes it happen. The following image shows a hierarchical WebGrid with several changes on each table. The pending changes can be easily recognized by its visual style and row header's indicator. |
When batch update feature is enabled in WebGrid, it will be automatically applied globally to include all child tables.
The batch update feature is supported in hierarchical WebGrid, regardless of the datasource type. That means no matter what your WebGrid is bound to - either it is a DataSet object, a hierarchical custom object, or an ISDataSource object - the batch update will always work in the same way and consistent fashion.
The batch update includes specific support for hierarchical WebGrid such as:
- Maintain relations through referential integrity.
WebGrid requires the tables to have valid referential integrity, that's all it needs for batch update feature to work. The referential integrity is usually defined at DataSet level through Relationships object. WebGrid makes use of this information in hierarchical data processing as well as in batch update processing. Through referential integrity between each table, WebGrid will be able to store appropriate changes such as edits or deletes in the child table. -
Cascading Inserts.
One of the most challenging requirements in hierarchical editing is the ability to perform cascading inserts in batch update mode.
Cascading inserts essentially means that newly added rows in each linked table should be submitted at the same time in a single update process. From end user point, they require the ability to create the new row in parent table and continue to add its child rows - without having to physically create the parent row in the server.
SmartBatchUpdate is designed to fully support cascading inserts, making it easier and more efficient for end user to add new data across multiple child tables.
An example of cascading inserts in hierarchical WebGrid can be seen in the following illustration.
As illustrated in the above image, user can quickly add a new data in the Customers table, drill down the record (even though it's not existed in server yet), add two new records into Orders table, drill down the Order record again, and finally add records to the Order Details table.
The cascading inserts is made possible as SmartBatchUpdate smartly virtualizes the referential links and structure of each table, and intelligently generates the unique auto-generated values in the client side. See the red-boxed hints in above illustration.
WebGrid supports auto-generated values for both auto-increment data type such as Int32 and GUID type. WebGrid will automatically show (Auto) text for auto-increment fields.
When it comes to server-side processing, i.e. when user invoked Accept Changes command, WebGrid will automatically translate the new identity with the one resulted from the database inserts and map it recursively to the linked child rows. For more information, please see Updating to Physical Database.
Automatic Changes Preservation
As in the good tradition of WebGrid, SmartBatchUpdate is rigorously designed for the best user experiences. In simpler words, the batch update feature shouldn't limit end user to perform common data operations - especially the one that completely changes the current view.
For quick instances - data sorting, grouping or filtering are normally disabled when batch update feature is used. Some common reasons are that the changes are either too difficult to be maintained, or impossible to be preserved between view change.
SmartBatchUpdate takes data editing to a new height by allowing users to do what they used to do - column sorting, filtering, grouping, and even data paging - while simultaneously maintain the existing pending changes that they have made. |
WebGrid does not only maintain the existing pending changes when you work on different views of your data, it perfectly restores the visual styles and row state of your pending changes as in where it left off.
Automatic changes preservation, an integral feature of SmartBatchUpdate - enables many scenarios not possible to achieve in the past - dramatically enhances user productivity. For instance, it is possible to edit a record in page 1, then jump to page 3 and edit more records, then go back to page 1 and edit more fields on existing edited record.
Automatic changes preservation works on data operations that change the view completely, such as:
- Column Sorting
- Column Filtering
- Column Grouping
- Column Visibility/Position Changing
- Refresh and RefreshAll
- Child Table Loading
- Classic Paging
- Virtual Load Paging
This feature is enabled by default when batch update feature is enabled. There are no additional steps required by developers to activate this feature. |
Updating to Physical Database
SmartBatchUpdate provides sophisticated implementation to automate the batch updating process to the physical database.
The automatic updating feature significantly reduces development time - as you are not required to write any codes to perform the batch update, or very minimal efforts when you need to customize the updating process in more advanced scenarios. |
To understand the physical updating concept better, please see the following illustration.
Understanding Batch Update Processes
As shown in the illustration above, the physical update has several processes such as detailed in the following:
-
Automatic object updates
This setting is enabled by default. This feature will attempt to automatically apply the submitted pending changes to the intermediate data source that hold the objects during the binding process.
For instance, when WebGrid is bound to DataSet or DataTable, your pending changes will be applied and then mapped to your data source. This enables you to simply call a line of code to perform the physical updates via DbAdapter.
In more advanced scenario, such as when WebGrid is bound to unstructured data source or custom object, you can disable this feature by setting the AutomaticObjectUpdates property in BatchUpdateSettings to false.
In addition to single table support, this feature is also designed to support nested hierarchical tables that linked through Referential Integrity. This feature makes advanced scenarios possible such as cascading inserts and other scenarios related to hierarchical tables.
Please note that WebGrid doesn't perform physical update in this process.
-
BatchUpdate server side event
WebGrid provides a new server side event named OnBatchUpdate, which is invoked when the pending changes are required to be submitted to physical database.
When bound to data source other than data source controls, developers can handle OnBatchUpdate server side event to write the codes required to update the changes into physical database.
When bound to updatable data source controls - such as AccessDataSource, ObjectDataSource, and others - WebGrid will handle all physical updates automatically, given that ReturnValue is true in OnBatchUpdate event. The ReturnValue is true by default, which can be set to false to cancel automatic physical updates.
OnBatchUpdate server side event provides BatchUpdateEventArgs in the event argument, which is useful for developers who would like to customize the physical updating process, such as in the case of custom object binding.
The BatchUpdateEventArgs contains two properties: -
- PendingChanges
Returns a List<WebGridRowChanges> object.
Access this property to get all pending changes, regardless of the row state and tables. For more information about the object model, see Server-side Programmability.
- ReturnValue (Returns a Boolean value)
When bound to updatable data source controls, such as SqlDataSource, WebGrid automatically connects to the data source controls and invokes the update function to process the changes. You can set this property to false to prevent WebGrid to continue the automatic updates, such as in the case of failed validation or other business logic constraints. The following C# codes show how to update all changes in a flat WebGrid that bound to a DataSet object.
The following C# codes show how to update all changes in a flat WebGrid that bound to a DataSet object.
C# Copy Code void WebGrid1_BatchUpdate(object sender, BatchUpdateEventArgs e) { CustomersTableAdapter daCustomer = new CustomersTableAdapter(); dsNorthwind ds = (dsNorthwind)WebGrid1.GetCachedDataSource(); daCustomer.Update(ds); // updates all changes to database }
- PendingChanges
-
Partial errors support
In addition to solid batch update architecture and automatic object updates, SmartBatchUpdate is also equipped with support for partial errors, making it the most advanced and reliable solution for client-side data editing application.
Partial errors occurred when one or more changes are failed to be updated while there are also some successful updates. Partial errors will not occur when all changes are failed.
With partial errors support, user can make changes with confidence, without have to worry that error in one of the changes will cause all changes to fail. This means that WebGrid is able to isolate erroneous changes, and continue to update the next changes that are unrelated to the previously failed changes update.
The following image shows a WebGrid with partial errors response. The error detail for each failed updates are shown in the message box, making it easy for end user to review and revise the errors.
For more control over partial errors response in the client side, you can handle the OnBatchUpdateSuccess client side event and access the rowErrorXml parameter to get the error detail on each failed update. For more information about client side usage, please see Client-side Programmability.
Various Datasource Support
WebGrid 7 supports physical database updates in various scenarios, such as when bound to different type of datasource, hierarchical tables configuration, and more. The following list describes the supported scenarios in more details:
- Traditional Binding (ADO.NET DataSet and DataTable)
When bound to ADO.NET-compatible data source such as DataSet and DataTable, you will need to write codes in OnBatchUpdate server side event to update the changes to database.
However, the required codes should be very minimal as ADO.NET already implemented batch update at data access level. Developers will then be able to simply invoking a single Update method to process all changes, which were previously mapped during Automatic Object Updates process.
The following C# codes show how to update all changes that bound to a DataTable object.
-
Declarative Binding (Datasource Control such as SqlDataSource)
Data source control is the most ideal data binding concept in ASP.NET that provides clear abstraction between UI and data logic. Introduced in .NET 2.0, data source control allows you to bind data in declarative markup, saving you from tedious tasks and lengthy codes.
SmartBatchUpdate takes advantage of data source control to the fullest. When you connect WebGrid to an updatable data source control, you don't need to write codes to handle the physical updates.
-
Hierarchical Traditional Binding (ADO.NET DataSet)
Similar to Traditional Binding, you are also required to handle OnBatchUpdate server side event to write codes to perform database updates.
Thanks to the automatic identity's mapping through referential integrity, WebGrid performs all the complex logics behind the scene, so that you only need to write a few lines of codes to update the dataset.
The following C# codes show how to update all changes in each table contained in the DataSet object.C# Copy Code void WebGrid1_BatchUpdate(object sender, BatchUpdateEventArgs e) { CustomersTableAdapter daCustomer = new CustomersTableAdapter(); OrdersTableAdapter daOrders = new OrdersTableAdapter(); Order_DetailsTableAdapter daOrderDetails = new Order_DetailsTableAdapter(); dsNorthwind ds = (dsNorthwind)WebGrid1.GetCachedDataSource(); // updates all changes per table adapter from the root table // to each child table in ordered sequence daCustomer.Update(ds); daOrders.Update(ds); daOrderDetails.Update(ds); }
-
Hierarchical Declarative Binding (ISDataSource)
As in flat WebGrid declarative binding, SmartBatchUpdate supports hierarchical WebGrid that is bound to ISDataSource control in the same way and consistent fashion.
With ISDataSource control, you are not required to write codes in order to perform physical update into the underlying database.
It is important to ensure that your ISDataSource instance has been properly configured to return new identity for each table in the event of insert. For more information, please see New Identity Insert in the section below.
-
Custom Object
In addition to built-in .NET data sources, SmartBatchUpdate is rigorously designed to support advanced enterprise scenarios, such as using the feature in conjunction with custom object data binding.
When bound to custom object collection - such as a list of Customer objects - you can disable automatic object updates feature. In this case, you are responsible to write codes to perform physical updates according to your business logic/model.
To learn more on how to use batch update feature in custom object scenario, please see Server-side Programmability.
New Identity Insert
One of the best practices in database design concept is to have at least one unique, auto-increment field in each table which acts as the row's identifier.
When you insert a new row to the table, the database will issue a new, unique identity value of the new inserted row. However, each database provider has different ways to retrieve the new identity's value. As such, Microsoft .NET Framework doesn't include built-in implementation to retrieve identity insert in its ADO.NET technology. |
SmartBatchUpdate relies heavily on row's identifier to differentiate each record in order to work properly. Therefore, developers should make sure that the new identity's value is correctly retrieved and passed to WebGrid during batch update processing.
The following list describes the techniques to retrieve the new identity's value in various data source type:
-
ADO.NET (DataSet).
ADO.NET, as the middle-tier data object provided in Microsoft .NET, does not contain database specific implementation in its data access level. As such, the design enables it to work with any database providers that support .NET Framework.
When a new row is inserted through DbAdapter compatible provider, it does
not return the new row's identity by default. Thus, developers are required to write additional codes to programmatically obtain the new row's identity.
The following C# codes show how to retrieve the new identity for Access or Sql database provider.C# Copy Code void WebGrid1_BatchUpdate(object sender, BatchUpdateEventArgs e) { CustomersTableAdapter daCustomer = new CustomersTableAdapter(); OrdersTableAdapter daOrders = new OrdersTableAdapter(); Order_DetailsTableAdapter daOrderDetails = new Order_DetailsTableAdapter(); dsNorthwind ds = (dsNorthwind)WebGrid1.GetCachedDataSource(); // Handle RowUpdated event of DataAdapter daOrders.DataAdapter.RowUpdated += new OleDbRowUpdatedEventHandler(DataAdapter_RowUpdated); daCustomer.Update(ds); daOrders.Update(ds); daOrderDetails.Update(ds); } void DataAdapter_RowUpdated(object sender, OleDbRowUpdatedEventArgs e) { // Conditionally execute this code block on inserts only. if (e.StatementType == StatementType.Insert) { if (e.Row.Table.TableName == "Orders") { OleDbCommand cmdNewID = new OleDbCommand("SELECT @@IDENTITY", e.Command.Connection); /* Retrieve the new identity and call UpdateRowIdentity to process the new identity. */ WebGrid1.GetTableByName("Orders").UpdateRowIdentity("OrderID", e.Row["OrderID"], cmdNewID.ExecuteScalar()); } } }
-
Codes Explanation:
- In OnBatchUpdate server side event, you write your codes that invokes physical database updates. In the sample above, the RowUpdated event is handled before any calls to Update method.
- The function delegate for RowUpdated will be invoked for each successful insert. The above codes perform checking on StatementType and TableName respectively.
- A new OleDbCommand object is created to perform select identity retrieval, based on existing connection instance. It's important that you use the existing connection instance in order to get the new identity properly. Again, note that the select identity retrieval statement above only works for Access and Sql-compatible provider.
- Finally, UpdateRowIdentity method of the respective WebGridTable instance is called, passing the identity's data member name, the current value of the OrderID, and the new identity's value resulted from the successive insert.
It's extremely important to call UpdateRowIdentity method to pass in the obtained new identity value. The method maps the new identity into each inserted row properly, which enables WebGrid to process the changes efficiently specifically in hierarchical configuration and more advanced scenarios such as cascading inserts. - Data source control.
Most data source controls that shipped with Visual Studio 2005 or 2008 do not support automatic identity retrieval. The only data source control that supports automatic identity retrieval is SqlDataSource. -
WebGrid extends the data source control further by providing automatic identity retrieval support for AccessDataSource, in addition to SqlDataSource. This means that if you bound WebGrid to either AccessDataSource or SqlDataSource, you don't need to write additional codes to retrieve the new identity. The following C# codes show how to retrieve new identity for ObjectDataSource control. The sample is referencing to Orders table in Northwind sample database. -
C# Copy Code [DataObjectMethodAttribute(DataObjectMethodType.Insert, true)] public int DoInsert(ref Nullable OrderID, string CustomerID, Nullable EmployeeID, Nullable OrderDate, Nullable RequiredDate, Nullable ShippedDate, Nullable ShipVia, Nullable Freight, string ShipName, string ShipAddress, string ShipCity, string ShipRegion, string ShipPostalCode, string ShipCountry) { this.Connection.Open(); // important int affectedRows = this.Insert(CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry); int identity = this.SelectIdentityQuery(); OrderID = identity; // pass the new identity into OrderID param this.Connection.Close(); return affectedRows; } public int SelectIdentityQuery() { OleDbCommandcmd = new OleDbCommand("SELECT @@IDENTITY", this.Connection); int newID = (int)cmd.ExecuteScalar(); return newID; }
At the WebForm (ASPX) page, make sure you reflect the InsertCommand with the new extended method name above. Furthermore, you'll need to add a new OrderID parameter in the InsertParameters collection. See the following sample:
-
Javascript Copy Code <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" ... InsertMethod="DoInsert" OnInserted="ObjectDataSource1_Inserted"> <InsertParameters> <asp:Parameter Direction="InputOutput" Name="OrderID" Type="Object" /> ... </InsertParameters> </asp:ObjectDataSource>
-
The following C# codes show how to access the output parameters that obtained during DoInsert command, and pass it to WebGrid for further processing.
-
C# Copy Code protected void ObjectDataSource1_Inserted(object sender,ObjectDataSourceStatusEventArgs e) { WebGrid1.SetOutputParameters(e.OutputParameters); }
-
-
By default, the Visual Studio-generated table adapter doesn't contain implementation to return new identity upon successive inserts. Thus, we created a new method to extend the table adapter's Insert functionality.
-
A new parameter OrderID with ref keyword is inserted into the first parameter of the extended Insert method. This parameter is used to hold the new identity value which is assigned during the process.
-
The SelectIdentityQuery method is used to obtain the row's new identity as the result of successive insert. This query is compatible with Access and Sql providers.
-
The extended Insert method name is assigned to the InsertCommand of the ObjectDataSource.
-
Handle OnInserted server side event of the ObjectDataSource to obtain the resulted output parameters and pass it to WebGrid for further processing.
-
Finally, adds a new <asp:Parameter> object into the InsertParameter collection of the ObjectDataSource. This new parameter is required to reflect the parameter signature of DoInsert method, which is used to hold the new identity value of OrderID column.
-
-
Intersoft Datasource Control (ISDataSource)
Intersoft's flagship ISDataSource control also works the same way and manner as ObjectDataSource, where it is serving as intermediate data class that bridge between User Interface and backend provider. As such, ISDataSource does not contain vendor-specific implementation in order to support various database providers supported by .NET Framework.
ISDataSource is the only provider in the market that supports multiple tables. As the result, WebGrid accepts only ISDataSource control for its hierarchical table feature.
To retrieve new identity in ISDataSource, you can use the same technique as in ObjectDataSource above. The only exception is that you can skip the fifth step above. ISDataSource doesn't require you to pass the output parameters to WebGrid, since it is tightly integrated with ISDataSource and thus it has exclusive capability to access ISDataSource instance through standardized interfaces.
Localization
The new batch update feature in WebGrid 7 introduces a dozens of new User Interface elements, which contains many new textual settings as well.
As in good tradition of WebGrid, all textual settings are customizable according to the culture specified by developer. Each textual setting can also be overridden individually. You can find the complete text settings in default.xml which is located in the Localization folder.
The following table lists the new text settings that you can customize.
Category | Text Setting Key | Default Text Setting Value (English) |
CommonText | PendingChanges | {0} pending change(s). |
DeletedRowNoEdit | Row marked as deleted cannot be modified. | |
DeletedRowNoExpand | Row marked as deleted cannot be expanded. | |
BatchUpdateSuccess | All changes have been successfully updated to server. | |
BatchUpdateSuccessWithPartialErrors | One or more changes are not updated due to server errors. | |
MessageBoxText | UnsavedPendingChanges | You have made one or more changes on WebGrid records. Any unsaved changes will lose. |
NotifyPendingChanges | There are {0} unsaved pending changes. Click Accept Changes button below to save changes. | |
UndoPendingChanges | Are you sure you want to undo all pending changes? | |
UndoSelectedPendingChanges | Are you sure you want to undo selected pending changes? | |
DeletedRowEditException | You cannot make changes to the row which parent has been marked as deleted. | |
DuplicateKeyException | The pending changes already contain a record with key '{0}' | |
PrimaryKeyEditException | Modification on primary key's field of pending changes is not allowed. | |
BatchUpdateException | An exception has occurred while processing batch update. please correct or undo your changes. \n\Exception details:\n{0} | |
BatchUpdatePartialException | WebGrid failed to update {0} out of {1} changes due to errors. Please review and correct your changes. \n\nThe following records were not updated:\n{2} | |
Tooltip | ModifiedRowState | Modified row |
AddedRowState | Added row | |
DeletedRowState | Deleted row | |
PendingChangesEmpty | There are no pending changes | |
PendingChangesExisted | There are {0} pending changes: {1} insert(s), {2} edit(s), {3} delete(s) | |
ReviewChanges | Review Pending Changes | |
UndoChanges | Undo All Changes | |
AcceptChanges | Accept All Changes | |
ContextMenu/Row | UndoSelection | Undo Selection |
DeleteSelection | Delete Selection |
Note: You may find empty text entries when using languages other than English. If you found empty entries on the language and culture that you are familiar with, please help us to translate the entries using the default.xml as the template and send it to feedback@intersoftpt.com. |
Compatibility with Other Features
As in every major release of WebGrid, every new feature and enhancement are designed to work in conjunction with existing features. There are, though, some conditions and scenarios where the enhancements are not applicable, such as due to behavior conflicts.
In addition to comprehensive hierarchical tables and client side editing support, SmartBatchUpdate is also designed to work with existing features. Some of noteworthy key features are such as listed in the following:
- All user interaction features, such as column resizing, moving, selection and context menu.
- All databound operations, such as sorting, grouping and filtering.
- Special support for column grouping, where newly added rows will remain visible and will be properly indented according to the group level.
- Data paging includes both classic paging and virtual load.
- Cell-select editing mode.
- Columnset layout mode.
- Column freezing.
- Auto-filter suggestion.
- Preview row.
- Self referencing.
Multiple Selection feature is also enhanced to work in harmony with batch update feature. When you select multiple rows that contain pending changes, the Undo Selection command will appear in context menu, allowing end user to quickly undo multiple pending changes. Also, when deletion feature is enabled and multiple rows are selected, Delete Selection will appear in the context menu.
All client side APIs and object models continue to work and function normally as published in the documentation. |
There are no unknown compatibilities with specific features that could cause errors or misbehaviors when batch update is enabled as far as the time of this writing.
Client-side Programmability
SmartBatchUpdates is a set of comprehensive object models and application programming interfaces (API), serving as the main foundation and architecture for the pending changes concept introduced in WebGrid 7.
All pending changes operation that invoked from WebGrid's user interface is also using the same set of APIs and interfaces. The result is a powerful and highly extensible client side batch editing architecture, which enables developers to further extend the functionality to address their complex business requirements.
The following sections describe the new classes, methods and client side events that introduced as core programming interfaces for the batch update feature.
New classes
WebGridBatchUpdateSettings
This class contains all settings and behaviors related to batch update feature.
Properties:
- AllowReviewChanges (bool)
- AllowUndoChanges (bool)
- AutomaticObjectUpdate (readonly, bool)
- PromptOnUndoAllChanges (bool)
- NotifyOnLostFocus (bool)
- HighlightChanges (bool)
WebGridCellData
This class holds the delta information of modified cell data.
Properties:
- Column (WebGridColumn object)
- OldValue (object)
- OldText (string)
- NewValue (object)
- NewText (string)
WebGridRowChanges
This class represents the changes for a row object.
Properties:
- RowState (readonly, string). Possible values: Added, Modified, Deleted.
- Element (readonly, HTMLRow object)
- Data (readonly, Array of WebGridCellData)
- Row (readonly, WebGridRow object)
- KeyValues (readonly, string)
- Table (readonly, WebGridTable object)
Methods:
- MergeChanges. Parameter: the row to be merged (WebGridRow object).
- GetExistingData. Parameter: the name of cell to retrieve (string).
New methods
Several methods have been added as extensions to provide batch update functionality. These methods will only be available when batch update feature is used.
Class | New Method | Parameters |
WebGrid | GetChangesCount ( Returns the count of all pending changes regardless of the state and table) | - |
UpdatePendingChangesStatus (Synchronize pending changes with Grid's user interface elements) | - | |
UndoallChanges (Undo all pending changes regardless of the state and table) | - | |
AcceptAllChanges (Accept all pending changes and submit them to server for batch update) | - | |
GetChanges (Returns a list of WebGridRowChange objects) | rowState (Specifies the state of the changes to get) | |
InvalidateChanges (Invalidate all pending changes to be reprocessed in the next synchronization) | - | |
ClearChanges (Clear and remove all pending changes regardless of the state and table) | - | |
WebGridTable | GetChanges (Return a list of pending changes that existed in this table) | rowState (Specifies the state of the changes to get) |
GetChangesCount (Returns the count of the pending changes in this table) | - | |
UndoChanges (Undo all pending changes in this table) | - | |
InvalidateChanges (Invalidate all pending changes in this table) | - | |
WebGridRow | GetChanges (Returns the changes made to this row) | rowState (Specifies the state of the changes to get) |
GetRowState (Returns the state of this row. It will returns Unmodified if this row has no changes) | - | |
InvalidateRowState (Invalidate the state of this row to be processed in the next synchronization) | - | |
UndoChanges (Undo changes made to this row) | skipUpdateStatus (Specifies whether to skip the status updating after undo) | |
AddPendingChanges (Mark changes made to this row and add it into pending changes collection) | isProgrammatic (Specifies whether the method is called by user code) | |
SetDeleted (Mark this row as deleted) | - | |
WebGridCell | SetChanges (Change the text and value of this cell) | text (The new text to be set) value (The new value to be set. This parameter is optional, and only useful for valuelist column) |
New client side events
The following table describes the new client side events related to batch update feature.
Event Name | Description | Parameters |
OnUndoChanges | Fired when a row changes is about to be undo'ed | controlId, rowObject (The row to be undo'ed) |
OnUndoAllChanges | Fired when undo all changes command is performed. | controlId |
OnAcceptAllChanges | Fired when accept all changes command is performed | controlId |
OnAddPendingChanges | Fired when a pending changes is about to be added | controlId, table (The table on which pending changes is added to), rowChange (The tow change object) |
OnRemovePendingChanges | Fired when a pending changes is about to be removed | controlId, table (The table on which pending changes is added to), rowChange (The row change object) |
OnBatchUpdateSuccess | Fired when batch update operation has been successfully completed | controlId, hasPartialErrors (Whether the batch update contains one or more errors), partialErrorsXml (The xml document contains partial errors data) |
Server-side Programmability
As in client-side, the same set of new classes and methods have also been added to server-side. This enables reliable synchronization between client-side and server-side, which results in consistent interfaces and elegant objects design.
For shared set of the new classes, methods and properties; please refer to Data editing with new Batch Update mode section above.
The following list shows additional methods to perform server-side related tasks.
- WebGrid class.
Methods:
- GetChanges()
Returns all pending changes regardless of the row's state and table.
- GetChanges(RowState rowState)
Returns all pending changes with given row state.
- PerformBatchUpdate(bool throwExceptionOnError)
Processes changes and updates it to physical database programmatically.
- GetBatchUpdateExceptions()
Returns one or more exceptions that occurred while processing batch update.
- AddBatchUpdateException(WebGridBatchUpdateException exception)
Adds an exception when a batch update-related error occurred. Use this method to take advantage of partial error support in custom object updating scenario.
- Events:
- OnBatchUpdate. Provided BatchUpdateEventArgs as the event argument.
This event will always be invoked when batch update feature is enabled. This event is required to be handled for traditional and custom object binding. You can cancel WebGrid for further processing by setting false to its ReturnValue.
- WebGridTable class.
- Methods:
- GetChanges(RowState rowState)
Returns all pending changes in this table, given the row state.
- UpdateRowIdentity(string dataMember, object originalValue, object processedValue)
Updates and maps new identity of successive row inserts to intermediate objects in the data source. This method is required for traditional and custom object binding.
The provided server side APIs, as described above, enables you to programmatically work against pending changes data that submitted from client-side.
Several scenarios that can be achieved by using the provided APIs:
-
Get the pending changes per table and per row state for further processing in your business object level.
You can use GetChanges method at WebGrid or WebGridTable object to get the desired changes.
The RowState enumeration includes the following values: Added, Modified and Deleted. You can query the changes based on one or multiple RowState.
For example, the following C# codes show how to query pending changes for Added and Modified state:
C# Copy Code List<WebGridRowChanges> changes = WebGrid1.RootTable.GetChanges(RowState.Added | RowState.Modified); foreach (WebGridRowChanges change in changes) { // process each changes }
Note that the pending changes data will not be submitted on WebGrid's FlyPostBack actions for performance wise. The changes will be available upon the following conditions:
-
- Full Postback.
- Accept Changes FlyPostBack action.
- ASP.NET AJAX callback.
-
Perform batch update on a server-side button click. In some cases, you might prefer to have your own button to process the pending changes, in addition to the user interface provided by WebGrid.
You can achieve this task by calling PerformBatchUpdate method available in WebGrid object. See the following C# sample:
C# Copy Code private void Button1_Click(object sender, EventArgs e) { WebGrid1.PerformBatchUpdate(true); }
-
Process pending changes programmatically and call your custom data access method to perform physical update. This scenario is especially useful when you bind WebGrid to custom object collection instead of dataset or datasource control.
The following C# codes show how to use many of the server-side methods to iterate each change and update it using custom data access layer.
C# Copy Code protected void WebGrid1_BatchUpdate(object sender, BatchUpdateEventArgs e) { foreach (WebGridRowChanges rowChanges in e.PendingChanges) { CustomObjects.Customer customer = null; try { switch (rowChanges.RowState) { case RowState.Added: customer = new CustomObjects.Customer(); MapChangesToObject(rowChanges.Data, customer); DataLayer.InsertCustomer(customer); break; case RowState.Modified: customer = DataLayer.GetCustomer(rowChanges.KeyValue.ToString()); MapChangesToObject(rowChanges.Data, customer); DataLayer.UpdateCustomer(customer); break; case RowState.Deleted: customer = DataLayer.GetCustomer(rowChanges.KeyValue.ToString()); DataLayer.DeleteCustomer(customer); break; } } catch (Exception exp) { // adds the Exception to batch update list to take advantage of WebGrid's partial errors support. WebGrid1.AddBatchUpdateException( newWebGridBatchUpdateException(rowChanges, new Exception("Record '" + rowChanges.KeyValue.ToString() + "' has error '"+ exp.Message + "'", exp))); } } }
C# | Copy Code |
---|---|
private void MapChangesToObject(List data, CustomObjects.Customer customer) { foreach (WebGridCellData cellData in data) { string newText = cellData.NewText; switch (cellData.Column.DataMember) { case "CustomerID": customer.CustomerID = newText; break; case "Address": customer.Address = newText; break; ... } } } |
Codes Explanation:
- In custom object scenario, developers often have their own data access layer to perform data management such as select, inserts, updates and deletes. Thus, you need to handle OnBatchUpdate server side event to process the changes as shown in above sample codes.
- You can access all pending changes from e.PendingChanges, which is List<WebGridRowChanges>.
- You iterate on each WebGridRowChanges. Then perform update based on the RowState value.
- Notice that we used strongly-typed custom object to perform data update in elegant fashion. For add and modified changes, you need to map the changes into the object accordingly. In the sample above, it is done with MapChangesToObject function.
- Call AddBatchUpdateException when an exception occurred. This enables the codes to continue updating the other records. This error handling is also taking advantage of partial errors support.
Getting Started
Getting Started
Overview
WebGrid Features Overview
Other Resources
Walkthrough Topics
How-to Topics