Saturday, March 10, 2012

Search data from DataTable using LINQ ASP.Net


Here I have shown how LINQ can use to find data from DataTable. Here i have used SQLServer 2005 database for database operation. Using sql query I am fetching data from database and after that the data is store into a data table. And at last I have used LINQ query to fetch my desire data from DataTable.



Step 1) Copy and paste below code and don't forget to change database connection code according to your system setting.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{

    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    SqlDataReader rd;
    public string query;

    protected void connection()
    {
        con.ConnectionString = "server=.\\SQLEXPRESS; integrated security=SSPI; initial catalog=sourav;";
        con.Open();
        cmd.Connection = con;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        connection();
        SqlDataAdapter ad = new SqlDataAdapter("select * from loginfo",con);
        DataTable dt = new DataTable("dt");
        ad.Fill(dt);

        int namec =(from c in dt.AsEnumerable()
                    where c.Field<string>("username") == "sourav"
                    select c).Count();

        this.Label1.Text="Number of this name:- "+  namec.ToString() ;
       
    }
}

No comments:

Post a Comment