Library tutorials & articles

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.

Comments

  1. 22 May 2007 at 05:25
    I didn't like any of the solutions to this problem until I came up with this one...

    The solution is to bind the entire Child table to a bindingSource and that to a dataGridView.  In this case the child table would be the courses that the soldier registered for.

    Then, whenever a soldier is selected, store the selected row in a global variable, such as lastSelectedSoldierRow. Then, when that changes, you do a select on the table that connects the two. The registers table in this case. For example registerDataTable.Select("soldier_ID = " + lastSelectedSoldierRow.ID.ToString());

    Take all those rows and add the course Ids to a globally declared stringBuilder. Whenever a different soldier is selected, add -1 to the stringBuilder as an initializer. Then, for each additional course ID added to the stringBuilder, add a comma to the stringBuilder before it. You'll end up with something like "1,2,3,4,5,6". Next, set the child table's bindingSource.Filter to a that string like so: Filter = "ID in (1,2,3,4,5)".

    That will filter all the courses, down to the ones which belong to the soldier. Whenever a new course is added, append the ID to the stringBuilder and reset the filter.

    Here's an example scrap of source code from my own project. It's messy, but may be helpful to somebody if the above wasn't enough.

    StringBuilder settingsFilterSB = new StringBuilder();
            private void dataGridViewComputers_SelectionChanged(object sender, EventArgs e)
            {
                if (this.dataGridViewComputers.SelectedRows.Count == 1 || this.dataGridViewComputers.SelectedCells.Count > 0)
                {
                    object dataBoundItem;
                    if (this.dataGridViewComputers.SelectedRows.Count == 1)
                        dataBoundItem = this.dataGridViewComputers.SelectedRows[0].DataBoundItem;
                    else
                        dataBoundItem = this.dataGridViewComputers.Rows[this.dataGridViewComputers.SelectedCells[0].RowIndex].DataBoundItem;
                    lastSelectedPcRow = (CallistoDataSet.ComputerOrGroupRow)((DataRowView)dataBoundItem).Row;

                    settingsFilterSB = new StringBuilder();
                    settingsFilterSB.Append("-1");
                    int selectedPcId = lastSelectedPcRow.ID;
                    foreach(CallistoDataSet.ComputerOrGroup2SettingsRow row in this.callistoDataSet.ComputerOrGroup2Settings.Rows)
                    {
                        if(row.ComputerOrGroup_ID == selectedPcId)
                            settingsFilterSB.Append("," + row.ComputerSettings_ID.ToString());
                    }
                   
                    this.computerSettingsBindingSource.Filter = "ID in (" + settingsFilterSB.ToString() + ")";


































  2. 04 Oct 2006 at 14:57

    Use a BindingSource control then use its Find method to get the index of the row.

  3. 31 Mar 2006 at 02:50

    I'm getting this error message: "Object reference not set to an instance of an object." when I try to run the code below. I've spent a couple days trying to figure out what it is, but I'm kind of new to vb.net and programming. I have two tables that look something like below (not all fields are shown). They should be related via the userID fields as a "many tasks to each user" relation. Any help on how to do this or why there is an error when I run the code would be greatly appreciated.

     

    Table: Users                        Table:Tasks                  

    userID                                 userID

    userName                           taskID

    password                           taskName

     

    Dim

    connection As New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0; data source=" & Application.StartupPath & "\blueteam2.mdb")

    Dim adpUsers As New OleDbDataAdapter("SELECT * FROM Users,Tasks,Projects", connection)

    Dim ds As New DataSet

    Try

    adpUsers.Fill(ds, "Users")

    ds.Relations.Add("UserTasks", ds.Tables("Users").Columns("userID"), ds.Tables("Tasks").Columns("userID"))

    dgUsers.SetDataBinding(ds, "Users.userID")

    dgTasks.SetDataBinding(ds, "Tasks.userID")

    Catch ex As Exception

    MessageBox.Show(ex.Message, "Admin Main Form Load")

    End Try

     

  4. 24 Sep 2005 at 18:54
    Well, not really. I'm exagerating a litte bit

    Anyway, I just want to thank you for this nice and realy usefull article.
    I not only got the relationships shown in a DataGrid, but also I could
    modify them through the DataSet.
  5. 27 Jul 2005 at 14:46

    try  
    Private view As  DataView = m_ds.Tables("Stuff").DefaultView


    But anyway I think that the trick is that the field ID is PK

  6. 13 Jul 2005 at 22:11

    I tried your code but the dv index is out of sync with the bm index. Please explain. You can email me at glenn_r@shaw.ca.



    Here my challenge. I have reference to a datarow in a datatable. I want the set the bindingcontext position to that datarow. How can I do this? When I sort the dataview it goes out of sync with the datatable index returned when I use the dv find method.


    Thanks,
    Glenn

  7. 04 Mar 2004 at 07:41
    I think the program is cool and understanding
  8. 01 Jan 1999 at 00:00

    This thread is for discussions of Winforms Data Binding Lessons Learned.

Leave a comment

Sign in or Join us (it's free).

Roy Osherove 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 topics, ...

Related podcasts

  • xpert to Expert: Inside Concurrent Basic (CB)

    "Concurrent Basic extends Visual Basic with stylish asynchronous concurrency constructs derived from the join calculus. Our design advances earlier MSRC work on Polyphonic C#, Comega and the Joins Library. Unlike its C# based predecessors, CB adopts a simple event-like syntax familiar to VB progr...

We'd love to hear what you think! Submit ideas or give us feedback