user7299597
user7299597

Reputation:

Search using linq

I have one Textbox, Button and Gridview; I want to Search in multiple columns. It works but of course in the last case only and ignores the above, so i need something when any case has value exist in my database will filter it. What should i do to make it possible? This my code.

protected void btn_search_Click(object sender, EventArgs e)
{
    Item item = new Item();

    //Search by item_name
    using (SupermarketEntities1 DB = new SupermarketEntities1())
    {
        item.item_name = txt_search.Text;

        itemGridView.DataSource = DB.Items.Where(x => x.item_name .Contains( item.item_name))
            .Select(x =>new {
                    x.item_id,
                    x.item_name,
                    x.item_unit,
                    x.Department.depart_name,
                    x.prod_date,
                    x.exp_date,
                    x.sale_price,
                    x.purchase_price,
                }).ToList();
        itemGridView.DataBind();
    }

    //Search by item_unit
    using (SupermarketEntities1 DB = new SupermarketEntities1())
    {
        item.item_unit = txt_search.Text;

        itemGridView.DataSource = DB.Items.Where(x => x.item_unit.Contains(item.item_unit))
            .Select(x => new {
                x.item_id,
                x.item_name,
                x.item_unit,
                x.Department.depart_name,
                x.prod_date,
                x.exp_date,
                x.sale_price,
                x.purchase_price, 
            }).ToList();
        itemGridView.DataBind();
    }

    //Search by sale_price
    using (SupermarketEntities1 DB = new SupermarketEntities1())
    {
        item.sale_price = Convert.ToDecimal(txt_search.Text);

        itemGridView.DataSource = DB.Items.Where(x => x.sale_price == item.sale_price)
            .Select(x => new
            {
                x.item_id,
                x.item_name,
                x.item_unit,
                x.Department.depart_name,
                x.prod_date,
                x.exp_date,
                x.sale_price,
                x.purchase_price                  
            }).ToList();
        itemGridView.DataBind();
    }

Upvotes: 0

Views: 202

Answers (1)

David
David

Reputation: 218798

The operator you're looking for is the logical or operator: ||

In your .Where() clause, you would check if any of the values match. Something like this:

DB.Items.Where(x =>
    x.item_name.Contains(item.item_name) ||
    x.item_unit.Contains(item.item_unit) ||
    x.sale_price == item.sale_price)

So build your item object however you need to, then have a single LINQ query with all of the comparisons in a single .Where() clause, and set the results of that query to your data source.

Upvotes: 1

Related Questions