GridView and DetailsView Events


You've seen that the data source controls support events allowing you to hook into the data process, but the data display controls also support a variety of events. Some of these events are similar to those on the data source controls, and are for data modification. For example, the GridView control has RowDeleting and RowDeleted events, and the DetailsView has ItemDeleting and ItemDeleted. While it might seem odd that both the data source controls and the display controls have similar events, you have to remember that while these controls work together, they are not dependent upon each other. Data source controls are an interface to the data, allowing many controls to bind to them, while display controls don't have to fetch their data from the data source controls. For this reason, there are events on both types of controls that allow interaction with the data flow.

Handling GridView Update Events

For the GridView control, both the Updating and Updated events provide access to details being updated. The event procedure parameter has properties Keys, OldValues, and NewValues, which provide a way to access the data being sent back to the database. Prior to the command execution, you could examine the values, perform validation, and cancel the update if necessary, as shown in the code snippet here:

protected void GridView1_RowUpdating(object sender,                          GridViewUpdateEventArgs e) {   if (!IsNumberic(e.NewValues("Price")))   {     e.Cancel = true;     MessageLabel.Text = "Price must be a number";   } }


This checks the RowIndex that identifies the row being updated. If the row value for the UnitPrice column is not numeric, the update is cancelled. If you want to take the grid out of edit mode, you can set the EditItemIndex property of the grid to 1 (the same technique applies with selections using the SelectedIndexsetting it to 1 takes the grid out of select mode).

The NewValues property is a dictionary containing all of the new values being sent to the data store, and OldValues contains the old values.



ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net