2

ProductModel.cs: (class)

public List<Product> GetSearchedProduct (string Name)
{
    try
    {
        using (garagedbEntities db = new garagedbEntities())
        {
            List<Product> products = (from x in db.Products
                                      where x.Name LIKE @txtSearch
                                      select x).ToList();
            return products;
        }
    }
    catch (Exception)
    {
        return null;
    }
}

search.aspx:

 <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"   AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:Button ID="btnSearch" runat="server" Text="Button" OnClick="btnSearch_Click" />

 <br />

<asp:Panel ID="pnlProducts" runat="server">
    <br />
</asp:Panel>
    <div style="clear:both"></div>

This is my search.aspx file. Actually I want to get the name of the product from TextBox then pass it to method which retrieves the products.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Ali Irfan
  • 33
  • 4

1 Answers1

5

In linq you should use Contains:

List<Product> products = (from x in db.Products
                           where x.Name.Contains(Name)
                           select x).ToList();

Edit: To use method you should create a new instance of ProductModel and then call the GetSearchedProduct method and send the txtSearch as a parameter to it. Like this:

protected void btnSearch_OnClick(object sender, EventArgs e)
{
    ProductModel pr = new ProductModel();
    var result = pr.GetSearchedProduct(txtSearch.Text);
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 2
    @AliIrfan I'm guessing you want to use the `Name` parameter you are passing into your method there. Note that `Contains` will be the same as putting a % wildcard at the beginning and end of the string in a SQL query. – juharr Jan 07 '16 at 19:40
  • Great ! it works ! THANKS ALOT MATE – Ali Irfan Jan 07 '16 at 20:48