How to do advance search using LINQ? Part #7


Here is the easiest way to do this task

Step1: Create a DataClassesDataContext using  “LINQ to SQL Class”.

Step2: Take a Gridview control in aspx page

Step3: Write the dynamic query using “Lamda Expression” like this

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

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

protected void Page_Load(object sender, EventArgs e)
{

}
protected void BtnSearch_Click(object sender, EventArgs e)
{
string EmpName = txtEmpName.Text;
string EmpSal = txtEmpSal.Text;

DataClassesDataContext dc = new DataClassesDataContext();

var query = from m in dc.tblEmps
select m;

if (!string.IsNullOrEmpty(EmpName))
{

query = query.Where(m => m.EmpName == EmpName);

}
if(!string.IsNullOrEmpty(EmpSal))
{
query=query.Where(m=>m.EmpSal==EmpSal);
}

GridView1.DataSource = query;
GridView1.DataBind();

}
}

Then you will get output like this

If you have some better way to do this task. Please share with me.

Thank you.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: