Let's say that we have a grid bound to the Courses table, but we don't want the user to edit a course that has already started. We have a StartDate column in the Courses table, so all we need to do now is know when a user has changed a value and cancel that edit if needed.
The way to do this is by reacting to the DataTable's RowChanging
event. This event is thrown when one of the Selected DataRow's columns is edited. Here's the code:
AddHandler ds.Tables("Courses").RowChanging, New DataRowChangeEventHandler(AddressOf OnRowChange)
Private Sub OnRowChange(ByVal sender As Object, ByVal e As DataRowChangeEventArgs)
If IsInProgress(e.Row) Then
Throw New Exception("Course Is Already In Progress")
End If
End Sub
Private Function IsInProgress(ByVal row As DataRow) As Boolean
'code to determine if the current Course is in progress
End Function
The next part is interesting: to cancel the editing, I need to throw an exception. This exception is caught by the DataGrid and shown to the user. Whatever text you write in the exception message is displayed to the user in a message box followed by a question whether they would like to cancel or edit the new value. By the way, this event can also be used to discover new rows. You can also register to the RowDeleting
event of the data table to receive notification of a row's deletion, but you cannot cancel that action from within the event. This is a bit more complicated and is explained in the next lesson. You can use the DataRowChangeEventArgs.Action
property to determine what action was taken for this even to occur: Deleted
, Changed
, Added
, and so on.
Comments