How to Bind GridView using linq in Asp.Net - ProgramIdea

How to Bind Gridview using linq in Asp.Net

Here we are binding a GridView by using linq. See below, how to add linq in your project.

Points Of Remember:

1. Add Linq to Sql page (.dbml) in your project.

2. Connect to the Database.

3. Drag your tables on linq page (.dbml).

4. Build the project.

<!DOCTYPE html>


<html xmlns="">

<head runat="server">

    <title>Bind GridView by using Linq</title>



    <form id="form1" runat="server">


         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"

               CellPadding="4" ForeColor="#333333" Width="600px">


                <asp:BoundField DataField="Name" HeaderText="Name" />

                <asp:BoundField DataField="Branch" HeaderText="Branch" />

                <asp:BoundField DataField="City" HeaderText="City" />


            <HeaderStyle BackColor="#7961da" Font-Bold="True" ForeColor="White" />        

            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />






C# Codes:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;


public partial class GridView_How_to_bind_GridView_by_using_Linq : System.Web.UI. Page


    // Create object of linq datacontext

    DataClassesDataContext db = new DataClassesDataContext();


    protected void Page_Load(object sender, EventArgs e)


        if (!IsPostBack)






    protected void BindGridView()


        // linq query

        var data = from i in db.tbl_students

                   select i;


        if (data != null)


            GridView1.DataSource = data;





Output :