Work With LINQ To SQL

Steps to work with LINQ to SQL or OR-Mapping tool to display the data in DataGridView.

Step1: Creating DBML file,

Create Windows Forms Application.

new

Go to Solution Explorer, with right mouse button click add, and then click New Item.

rm

Select data from Visual C# installed item and then select LINQ to SQL classes Template. Type the file name within parenthesis Employee.dbml and click Add,

link

This will create employee DBML file (shown in red Box).

red Box

Step 2: Connecting to database

Go to server explorer, select data connection, with right mouse button click on add connection. Then change select Microsoft SQL server data service.  select the data provider as .NET frame work data provider for SQL server.

After that click OK, type the server name, select Use SQL Server Authentication and then enter username password or (you can also select Use Windows Authentication ), activate the check box 'Save my password'.
 
Now select the database name EmployeeDetails and click on OK.

connection

Double click on 'Tables', drag the table Emp on to the left side part of DBML file. This will create class with name EMP and properties as same name as table fields.

emp

Design the windows form and write the following code,

form

  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.ComponentModel;  
  4. usingSystem.Data;  
  5. usingSystem.Drawing;  
  6. usingSystem.Linq;  
  7. usingSystem.Text;  
  8. usingSystem.Threading.Tasks;  
  9. usingSystem.Windows.Forms;  
  10.   
  11. namespaceWindowsApplicationLTSQL  
  12. {  
  13.     publicpartialclassForm1: Form  
  14.     {  
  15.         EmployeeDataContextobjdc = newEmployeeDataContext();  
  16.         public Form1()   
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.         privatevoid Form1_Load(object sender, EventArgs e)  
  21.         {  
  22.             dataGridView1.DataSource = objdc.Emps;  
  23.         }  
  24.         privatevoidbtnSave_Click(object sender, EventArgs e)  
  25.         {  
  26.             objdc.SubmitChanges();  
  27.             MessageBox.Show("Data is updatated to Database ");  
  28.         }  
  29.     }  
  30. }  
Recap: For working with LINQ to SQL for displaying the data in GridView here are the steps,

Step 1: Create dbml File.

Step 2: Connecting to database.