Winforms Data Binding Lessons Learned

Reacting to Illegal Row Editing in a DataGrid

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.

You might also like...

Comments

About the author

Roy Osherove Israel

Roy Osherove has spent the past 6+ years developing data driven applications for various companies in Israel. He's acquired several MCP titles, written a number of articles on various .NET topic...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“An expert is a man who has made all the mistakes that can be made in a very narrow field” - Niels Bohr