Thursday, February 12, 2015

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="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Bind GridView by using Linq</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
               CellPadding="4" ForeColor="#333333" Width="600px">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Branch" HeaderText="Branch" />
                <asp:BoundField DataField="City" HeaderText="City" />
            </Columns> 
            <HeaderStyle BackColor="#7961da" Font-Bold="True" ForeColor="White" />       
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
          </asp:GridView>
    </div>
    </form>
</body>
</html>

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)
        {
            BindGridView();
        }
    }

    protected void BindGridView()
    {
        // linq query
        var data = from i in db.tbl_students
                   select i;

        if (data != null)
        {
            GridView1.DataSource = data;
            GridView1.DataBind();
        }
    }
}

View output :



Process of add linq to you application :


Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments. Stay tuned and stay connected for more technical updates."

No comments:

Post a Comment