2017-03-27 91 views
0

我有一個文本框,按鈕和GridView;我想在多列中搜索。 它的工作原理,但當然在最後一種情況下,並忽略了上述情況,所以當我的數據庫中存在任何值的情況下需要進行篩選。我該怎麼做才能做到這一點? 這是我的代碼。使用linq搜索

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(); 
    } 

回答

1

你要找的操作是邏輯操作:||

在你.Where()條款,你會檢查是否有任何值匹配的。事情是這樣的:

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

因此,建立你的item對象無論你需要,那麼就得在.Where()條款與所有比較的 LINQ查詢,而查詢的結果設置爲您的數據源。

+0

它的工作,但同樣的問題,如果x.sale_price == item.sale_price)情況下存在所以我哈希它,它工作正常 – hazem