Let's write a page that provides a master/detail view of the Customers table in the Northwind database using a DataGrid and a DetailsView control. The page is shown in Figure 5 below.
Figure 5. A sample page to demonstrate master/details view
The following code snippet illustrates a possible handler for the UpdateCommand event fired when the user clicks to save changes made to a record. For simplicity, the handler saves only the Country field, but the mechanism shown can easily be extended to any other field.
Private Sub DetailsView1_UpdateCommand( _
ByVal sender As System.Object, _
ByVal e As Expoware.DetailsViewUpdateEventArgs) _
Handles DetailsView1.UpdateCommand
' Prepare the update statement (only field Country)
Dim cmdText As String = "UPDATE customers SET country=@country " + _
"WHERE customerid=@customerid"
Dim conn As New SqlConnection("...")
Dim cmd As New SqlCommand(cmdText, conn)
cmd.Parameters.Add("@country", e.DataItems("country"))
cmd.Parameters.Add("@customerid", e.DataItems("customerid"))
' Execute the statement
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
' Continue update
e.NewMode = e.CurrentMode
' Reload and refresh data
BindData()
End Sub
Note the use of the DataItems collection to retrieve field values as the user edited them in the form