ARTICLE

Binding Gridview using LINQ

Posted by Gohil Jayendrasinh Articles | ASP.NET Programming March 12, 2009
Tags: GRIEDVIEW, LINQ
This article shows how to Bind Gridview using Linq.
Reader Level:


Here I am going to show how you can bind the GridView with Linq.
First let us have a look to our aspx page.
/*.aspx page*/

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Untitled Page</title>

</head>

<body>

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

    <asp:ScriptManager ID="ScriptManager1" runat="server">

    </asp:ScriptManager>

    <div>

        <table align="center">

            <tr>

                <td>

                    <asp:Label ID="Label1" runat="server" Text="Region:"></asp:Label>

                </td>

                <td>

                    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

                            <ContentTemplate>

                                <asp:DropDownList ID="ddlregion" runat="server" AutoPostBack="True"

                                    onselectedindexchanged="ddlregion_SelectedIndexChanged">

                                </asp:DropDownList>

                            </ContentTemplate>

                    </asp:UpdatePanel>                   

                </td>

            </tr>

            <tr>

                <td>

                </td>

                <td>

                     <asp:UpdatePanel ID="UpdatePanel2" runat="server">

                            <ContentTemplate>

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

                                    BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"

                                    CellPadding="4" ForeColor="Black" GridLines="Vertical">                                   

                                    <FooterStyle BackColor="#CCCC99" />

                                    <RowStyle BackColor="#F7F7DE" />

                                    <Columns>

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

                                        <asp:BoundField HeaderText="Country" DataField="country" />

                                        <asp:BoundField HeaderText="Region"  DataField="region"/>

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

                                    </Columns>                                   

                                    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

                                    <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

                                    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

                                    <AlternatingRowStyle BackColor="White" />

                                </asp:GridView>

                            </ContentTemplate>

                    </asp:UpdatePanel>

                    <asp:UpdateProgress ID="UpdateProgress1" runat="server">

                        <ProgressTemplate>

                            Loading...

                        </ProgressTemplate>

                    </asp:UpdateProgress>

                </td>

            </tr>

        </table>

    </div>

    </form>

</body>
</html> 
The code behind to fetch the records through linq and bind it to the GridView.
/*.cs file for Bind Gridview*/

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.SqlClient;

 

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

{

    connect connect = new connect(); // Connection class contain connection string.

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            Bindregiondata();

        }

    }

 

    private void Bindregiondata()

    {

        using (SqlConnection con = new SqlConnection(connect.Getconnection()))

        {

            con.Open();

            testLINQinfoDataContext db = new testLINQinfoDataContext();

 

            var regioninfo = from p in db.REGIONs

                             orderby p.regionname

                             select new

                             {

                                 regionid = p.regionid,

                                 regionname = p.regionname

                             };

 

            ddlregion.DataSource = regioninfo;

            ddlregion.DataTextField = "regionname";

            ddlregion.DataValueField = "regionid";

            ddlregion.DataBind();

 

            ddlregion.Items.Insert(0, "--Select Regioname--");

 

        }

    }

    protected void ddlregion_SelectedIndexChanged(object sender, EventArgs e)

    {

        using (SqlConnection con = new SqlConnection(connect.Getconnection()))

        {

            testLINQinfoDataContext db = new testLINQinfoDataContext();

 

            var employeeinfo = from p in db.EMPLOYEEINFOs

                               join c in db.COUNTRies

                               on p.countryid equals c.countryid

                               join r in db.REGIONs

                               on p.regionid equals r.regionid

                               join d in db.CITies

                               on p.cityid equals d.cityid

                               where p.regionid == Convert.ToInt32(ddlregion.SelectedItem.Value)

                               select new

                               {

                                   name = p.empname,

                                   country = c.countryname,

                                   region = r.regionname,

                                   city = d.cityname

                               };

 

            GridView1.DataSource = employeeinfo;

            GridView1.DataBind();

        }

    }

}
 

Login to add your contents and source code to this article
Article Extensions
Contents added by pavan sharma on May 21, 2013
post comment
     

in vb 2010, how do i do this? i want to use linq to connect to the db and also use linq to query it. 

So i have a form with a gridview. I add a datasource. Now i want to bind the gridview to the db using linq and linq for connection string.
 But when i configure the gridview to a datasource it  automatically configures dataset and connection string. How do i use linq to make the connection?
2. After that i want to use a linq query and display results in another gridview. How do i do that?
3. Where do i use the using system.data.linq statement in my app? on the form or in a seperate class?
4. how to use datacontext for this, where do i write it?New class or on same form? or Partial Class?

Posted by sam viper Dec 01, 2010

Thanks For sharing Knowledge.

Posted by Chandresh Pansuriya Apr 21, 2009
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter