Library tutorials & articles

Winforms Data Binding Lessons Learned

Reacting to Illegal Row Deletion in a DataGrid

This part is a little trickier than before, since you can't just throw an exception which is handled by the DataGrid. For some reason you have to go through some hoops to create this kind of functionality yourself. The first trick to understanding how to accomplish this is to understand how the DataGrid displays its data. You should notice that the DataGrid does not have any properties, such as AllowDelete or AllowAddNew. In fact, you can't control how your users should interact with the grid using any of the grid's properties (except Enabled). The trick is that the DataGrid is actually basing its interactivity level on an underlying DataView object to which it is bound. If you look at a DataView object, you should see that it does contain these kinds of properties. So, setting AllowDelete on the DataGrid's underlying DataView object to false disables delete functionality from the grid.

Now, the technique becomes pretty simple: we disable the AllowDelete property of the DataView and catch the KeyDown event of the DataGrid. If the KeyCode is that of the Keys.Delete key, we enable deletion on the DataView, delete the current data row, and disable deletion again until next time. Here's the code:

Private Sub grd_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles grd.KeyDown
    If e.KeyCode = Keys.Delete Then
        'check whether the current DataRow Course
        'is in Progress and cancel deletion if it is
        If IsInProgress(CType(GetGridCurrency().Current, DataRowView).Row) Then
            MsgBox("Already in progress")
        Else
            'Delete the current row
            EnableDelete(True)
            CType(GetGridCurrency().Current, DataRowView).Delete()
            EnableDelete(False)
        End If
    End If
End Sub

Private Function GetGridCurrency() As CurrencyManager
    'return the currency manager associated with the DataGrid
    Dim cm As CurrencyManager = BindingContext(grd.DataSource, grd.DataMember)
    Return cm
End Function

Private Sub EnableDelete(ByVal value As Boolean)
    'enable or disable AllowDelete on the
    'DataGrid() 's underlying DataView
    Dim cm As CurrencyManager = GetGridCurrency()
    Dim view As DataView = CType(cm.List, DataView)
    view.AllowDelete = value
End Sub

Notice that what I'm actually deleting is a DataRowView object, not a DataRow. This is because just like a data table has data rows, a DataView has DataRowViews corresponding to each DataTable row. Each DataRowView holds a property reference to the data row associated with it. Performing actions on a DataRowView is just like performing them on a DataRow object.

That's it. There's no way around this that I could find, but I have seen one other way to accomplish this functionality, by deriving a custom grid from the DataGrid and pre-processing WM_KEYDOWN messages before they arrive.

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, ...
AddThis

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...

Want to stay in touch with what's going on? Follow us on twitter!