ASP.Net : LINQ and DataSet

1. Create  Table (SQL Express)

mtv1

 

2. C# code (Page Behind)

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

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Linq_1 : System.Web.UI.Page
{

    SqlConnection cnn = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter ada = new SqlDataAdapter();
    
    protected void Page_Load(object sender, EventArgs e)
    {
     

     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        DataSet  ds= new DataSet();
        cnn.ConnectionString = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
        cmd.Connection = cnn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select  * from courses";


        ada.SelectCommand = cmd;
        ada.Fill(ds, "courses");
        

        // Bind GridView to Dataset
        //GridView1.DataSource = ds;
        //GridView1.DataBind();
        


        DataTable  dt= ds.Tables[0];

        // Bind GridView to Dataset
        //GridView1.DataSource = dt;
        //GridView1.DataBind();
        


       // var query = from r in dt.AsEnumerable()     where r.Field<string>("cname") == "BCA" select r.Field<string>("cname");
          
        var query = from r in dt.AsEnumerable()  where r.Field<string>("cname") == "PGDCA" select new { Code = (String)r["cname"] , Duration=(String)r["cduration"], ID =(Int64)r["cid"]};
        GridView1.DataSource = query;
        GridView1.DataBind();

    }
}

3. Web Form code( .aspx)

<%@ Page Language="C#"  %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <div>
        <asp:Button ID="Button1" runat="server" Text="Run LINQ" onclick="Button1_Click" />
        <br />
        <br />
   
        <asp:GridView ID="GridView1" runat="server"  HeaderStyle-BackColor="Green">
        </asp:GridView>
     </div>
    </center>
    </form>
</body>
</html>

4. Output..

mtv2

 

5. web.config

<configuration>

  <connectionStrings>
    <add name="Myconnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
     providerName="System.Data.SqlClient" />
   
  </connectionStrings>
 <system.web>
    	<compilation debug="true" targetFramework="4.0"/>
	</system.web>
</configuration>