Nov 7, 2008

Databinding and LINQ: Deleting a Row

There are a couple of ways to delete data when you use data binding coupled with LINQ to SQL. The examples assume you have a data context that maps the relationships between your tables. 
 Depending on what type of data validation you need to do and the type of widget you used will dictate which approach to take. If you have a data grid view and you don't need to validate anything you can just remove the current row from the grid. You should as a minimum make sure a single row has been selected.  I typically create a static method in my utility class for this and just pass in the grid of interest.
static public void GridSingleRowDelete(DataGridView theGrid)
{
    int row_count = theGrid.SelectedRows.Count;
    if (row_count == 1)
    {
        theGrid.Rows.Remove(theGrid.SelectedRows[0]);
    }
    else
    {
        if (row_count == 0)
        {
            MessageBoxActionNotAllowed("Please select one entire row first.",
                                       "Single Row Not Selected");
        }
        else if (row_count > 1)
        {
            MessageBox.Show("Only one row can be deleted at a time.");
        }
    }
}
If you need to do some database validity checks first you can easily get the current object from the binding source for the grid. For example, assume we have a datagrid with a collection of Jobs and the Jobs have many LineItems that may or may not be attached. You only want to allow Jobs to be deleted if they don't have any LineItems.
private void btnJobDelete_Click(object sender, EventArgs e)
{
     Job job_to_delete = (Job) jobBindingSource.Current;
     if (job_to_delete.LineItems.Count() > 0)
     {
         Utilities.MessageBoxActionNotAllowed("This job has attached line items. Please remove...");
     }
     else
     {
         if ( Utilities.DialogWarning("Are you sure...?","Delete?") == DialogResult.Yes)
         {
             Utilities.GridSingleRowDelete(dgJobs);
         }
     }
}
I wanted to post a follow up to this just to mention the DataBoundItem property. 
If you have a DataGridView and you need to get to the underlying object bound to a row
you can use the DataBoundItem property. For example:
foreach (DataGridViewRow dataGridViewRow in someDataGridView.SelectedRows)
{
    MyObject my_object = dataGridViewRow.DataBoundItem as MyObject;
    if (my_object != null)
    {
        //use my_object
    }
}

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.