Insert/Update/Delete in DataGridView using Linq in Windows Forms


This article will explain how to insert, update, delete records in datagridview using Linq.

Introduction:

This is a simple application that shows how to insert, update, and delete the records by using DataGridView.

Please check the link for how to add Linq to Sql classes to the project http://msdn.microsoft.com/en-us/library/bb384470%28v=VS.90%29.aspx

Following is the table with four columns I have used to bind the datagridview.

1.gif

Code:

Here is the code to bind the gridview. 

var getData = (from cstable in dbCnn.CSMembers
                              select cstable);
CSGridView1.DataSource = getData;

Once the above code is called the gridview with data looks like

2.gif 

Initially the buttons to insert update and delete are hidden when clicked on any cell the buttons are made visible. The CSID column has set to read only as it is set to identity specification where all the operations are done based on this column.

Here is the code to update the records and is called in btnUpdate click event 

var getData = (from cstable in dbCnn.CSMembers
               where cstable.CSID == CSID
               select cstable).Single();
getData.PointsEarned = PointsEarned;
getData.Name = Name;
getData.Type = Type;
dbCnn.SubmitChanges();

Cellclick event is used to get the current row and the CSID from the datagridview.

Here is the code to insert the records and is called in btnInsert click event 

CSMember csm = new CSMember();
if (csname != null && cstype != null && cspointsearned != null)
{
    csm.Name = csname;
    csm.PointsEarned = cspointsearned;
    csm.Type = cstype;
    dbCnn.GetTable<CSMember>().InsertOnSubmit(csm);
    dbCnn.SubmitChanges();
}

Here is the code to delete the record from database and is called in btnDelete click event.

for (int i = 0; i < CSGridView1.SelectedRows.Count; i++)
{
    using (var dbCnn = ConnClass.ConDB())
    {
        if (CSID != 0)
        {
            var getData = (from cstable in dbCnn.CSMembers
                           where cstable.CSID == CSID
                           select cstable).Single();
            dbCnn.CSMembers.DeleteOnSubmit(getData);
            dbCnn.SubmitChanges();
        }
    }
}

In the code for loop is used to delete the multiple records from the datagridview. 

Once the above code is called the output looks as

3.gif

Check the attachment for complete code along with mdf file.


Similar Articles