In a previous post, we covered Adding, Updating, and Refreshing Data in a Datagrid. We’re using LINQ to SQL and winforms.So, as promised, here’s how we delete records using LINQ and C# in a winform:


private void removeButton_Click(object sender, EventArgs e)
{

if (dgvProjectData.SelectedRows.Count > 0)

{
try
{
// Get the Company
var curCompany = GetRecord();

// Delete the contact.
lqMyDb.Companies.DeleteOnSubmit(curCompany);

lqMyDb.SubmitChanges();

btnRefresh_Click(null, null);

}

catch (InvalidOperationException io)
{
MessageBox.Show(this, (“Oops! you are trying to delete a record that no longer exists. Please refresh your records again.”), “Missing record …”);
}

catch (Exception ex)
{
MessageBox.Show(this, (“The following occred while trying to delete:” + ex.Message), “Delete Error…”);
}
}

else
{
MessageBox.Show(this, “You did not select a row to delete”, “Delete Error…”);
}
}

First, there is: if (dgvProjectData.SelectedRows.Count > 0)

We’re basically making sure we’re selecting a row. After which we “try” to get a specific record with this code: var curCompany = GetRecord();

Now we delete the company and submit the changes with the following code:

lqMyDb.Companies.DeleteOnSubmit(curCompany);

lqMyDb.SubmitChanges();

btnRefresh_Click(null, null);

What if there are problems? Well, we have catches in place for that:

catch (InvalidOperationException io)
{
MessageBox.Show(this, (“Oops! you are trying to delete a record that no longer exists. Please refresh your records again.”), “Missing record …”);
}

catch (Exception ex)
{
MessageBox.Show(this, (“The following occured while trying to delete:” + ex.Message), “Delete Error…”);
}

Finally, if they didn’t set a record to delete, then this messagebox will show:

MessageBox.Show(this, “You did not select a row to delete”, “Delete Error…”);

And that’s it. In my next post, I’ll show the drama that involves trying to display a company name in a combobox.

LEAVE A REPLY

Please enter your comment!
Please enter your name here