21 February 2014

Select Query in Linq


LINQ Select Query:
Below LINQ query will get the Students details from database where table "tbl_students"

var students = from stu in sqlObj.tbl_students
                       select new
                       {
                           stu.Id,
                           stu.Name,
                       };

Table data

Asp.net Code
<form id="form1" runat="server">
    <div>
    <center>
    <asp:GridView ID="gv1" runat="server"></asp:GridView>
    </center>
    </div>
    </form>

C#.net Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Select_Query : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        MydbDataContext sqlObj = new MydbDataContext();
        var students = from stu in sqlObj.tbl_students
                       select new
                       {
                           stu.Id,
                           stu.Name,
                       };
        gv1.DataSource = students;
        gv1.DataBind();
    }
}

OutPut


No comments:

Post a Comment