Monday, July 2, 2012

datatable filter using linq in asp.net c#.net

I go through lots of site for select query on DataTable. But most of the time I did not get a suitable solution. So, at last I use linq to filter data from datatable. So I share my code below:-



DataTable dt = new DataTable();
string sqlStatement1 = "select * from hsswith_view where cp_amount<='" + bug_amount + "' and no_of_days >='" + no_of_days + "' or ep_amount<='" + bug_amount + "' and no_of_days >='" + no_of_days + "'";
SqlCommand sqlCmd1 = new SqlCommand(sqlStatement1,connection); SqlDataAdapter sqlDa1 = new SqlDataAdapter(sqlCmd1);
sqlDa1.Fill(dt1);
var query = from r in dt1.AsEnumerable()
where r.Field("pax") == no_person
select new
{
entry_id = r["entry_id"].ToString(),
pax = r["pax"].ToString(),
package = r["package"].ToString(),
no_of_days = r["no_of_days"].ToString(),
cp_amount = r["cp_amount"].ToString(),
ep_amount = r["ep_amount"].ToString()
};
GridView1.DataSource = query;
GridView1.DataBind();


First of all I select data using one select query and fill it at datatable(dt1). Now I write linq query to extract data from dt1 DataTable and bind the values at GridView. These much.

No comments: