The optimistic concurrency feature simply acts as a safeguard against multiple, concurrent users overwriting each other's changes. It does not provide a means for alerting the user that his update or deletion was not propagated to the database due to the fact that the underlying data has since changed. That is, in our Jisun and Sam scenario in Figure 16.14, had optimistic concurrency been used, when Sam clicked the Update button, his changes wouldn't be submitted. By default, he'd receive no feedback; when the page refreshed, it would be back to its pre-editing state, but instead of seeing the year published as 2002, it would be set to 2005, with the author as Dave Yates. Ideally, it would be nice to alert Sam that his change was not saved because it would have overwritten another user's recent modifications. This can be accomplished by creating an event handler for the GridView's RowUpdated event. The RowUpdated event fires after the user has clicked the Update button and the GridView has submitted the update request to its data source control. The RowUpdated event handler is passed in as its second parameter an object of type GridViewUpdatedEventArgs, which includes a property called AffectedRows. This property, as you may have guessed, specifies how many rows were affected by the UPDATE statement issued to the database. If this value is 0, then the user's UPDATE did not succeed in finding any matches, either because the row has since been deleted, or optimistic concurrency is being used and another user has since modified the contents. In either case, we can display a message to the user when this scenario unfolds by using the following code in the ASP.NET page's source code portion: [View full width] Protected Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI .WebControls.GridViewUpdatedEventArgs) Handles GridView1.RowUpdated If e.AffectedRows = 0 Then LabelID.Text = "Your update was not committed either because the record no longer exists or another user recently made a change to this record and your update would have overwritten these changes." End If End Sub
To create the event handler for the GridView's RowUpdated event, go to the source code portion and select the GridView from the left drop-down list at the top of the screen and the RowUpdated event from the right drop-down list. |