Monday, 3 December 2012

how to search in gridview values using textbox C#


how to search in gridview values using textbox 

C# in ASP.NET


This example demonstrates how to search/query gridview using textbox .

Step 1) Add GridView and bind it to List of Customer History.

       <div style="width:600px;">
        <div style="float:right;"><font color="green;"><b>Search  String:</b></font>
<asp:TextBox ID="txtQuery" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /></div>

       <div style="float:right;"> 

<asp:GridView Caption="<h1 style='color:red;text-align:left;'>GridView Search using Textbox</h1>" CaptionAlign="Left"  ID="GridView1" runat="server" Width="568px" EmptyDataText="No data Found"></asp:GridView>

</div>
       </div>

in Page_Load Event

       List<CustomerOrdersHistory> listCustHist = null;
        List<CustomerOrdersHistory> searchList = new List<CustomerOrdersHistory>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Build some list with sample data
                Build_CustOrderHistResult_Data();
                //first time store it in Session Object
                Session["custHistory"] = listCustHist;
            }
            GridView1.DataSource = listCustHist;
            
            GridView1.DataBind();
        }

add a class called CustOrderHistResult.cs
public class CustOrderHistResult
{
public string ProductName{set;get;}
public int Total{get;set;}
}

Add following data to CustOrderHist
/Build CustOrderHistResult List
            if (listCustHist == null) listCustHist = new List<CustomerOrdersHistory>();
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Aniseed Syrup ", Total = 6 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Chartreuse verte", Total = 21 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Escargots de Bourgogne", Total = 40 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Flotemysost", Total=20 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Grandma's Boysenberry Spread", Total = 16 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Lakkalikööri", Total=15});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Original Frankfurter grüne Soße", Total=2});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Raclette Courdavault", Total=15});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Rössle Sauerkraut", Total=17});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Spegesild", Total=2});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Vegie-spread", Total=20});

Button search 
protected void btnSearch_Click(object sender, EventArgs e)

            String searchString = txtQuery.Text;

            if (Session["custHistory"] != null)
                listCustHist = (List<CustomerOrdersHistory>)Session["custHistory"];

            if (listCustHist != null && searchString != String.Empty)
            {
                foreach (CustomerOrdersHistory chList in listCustHist)
                {
                    System.Text.RegularExpressions.Match m=System.Text.RegularExpressions.Regex.Match(chList.ProductName, searchString);
                    if (m.Success)
                    {
                        searchList.Add(chList);
                    }
                    else
                    {
                        m = System.Text.RegularExpressions.Regex.Match(chList.Total.ToString(), searchString);
                        if (m.Success) searchList.Add(chList);
                    }
                    
                }
            }
            GridView1.EmptyDataText = "Search result is Nothing...";
            GridView1.DataSource = (searchString==String.Empty)?listCustHist:searchList; //if query string is empty display all records
            //else display search results
            //else no data found for search will be displayed.
            GridView1.DataBind();


Searching GridView data , Used Regular exp to match a  QueryString ,  I applied to all fields(2). You can replace Query Pattern to word boundary or restrict columns etc.,

Here is the OUTPUT





 Figure 1:  All data 
Figure 2:  searching for value 6

Figure 3: searching for   "spread"  as shown below

Figure 4:  Pass some junk value , it returns Search result is nothing..

Complete Source Code

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

namespace WebApplication1
{
    public partial class GridView_and_Search_EnityDataSource : System.Web.UI.Page
    {
        //we need 2 lists
        //1 for actual data
        //2 for search data
        List<CustomerOrdersHistory> listCustHist = null;
        List<CustomerOrdersHistory> searchList = new List<CustomerOrdersHistory>();
        protected void Page_Load(object sender, EventArgs e)
        {
            //System.Data.Linq.Table < CustOrderHistResult> custOrder = context.GetTable<CustOrderHistResult>();
            if (!IsPostBack)
            {
                //Build some list with sample data
                Build_CustOrderHistResult_Data();
                //first time store it in Session Object
                Session["custHistory"] = listCustHist;
            }
            GridView1.DataSource = listCustHist;
            
            GridView1.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            String searchString = txtQuery.Text;

            if (Session["custHistory"] != null)
                listCustHist = (List<CustomerOrdersHistory>)Session["custHistory"];

            if (listCustHist != null && searchString != String.Empty)
            {
                foreach (CustomerOrdersHistory chList in listCustHist)
                {
                    System.Text.RegularExpressions.Match m=System.Text.RegularExpressions.Regex.Match(chList.ProductName, searchString);
                    if (m.Success)
                    {
                        searchList.Add(chList);
                    }
                    else
                    {
                        m = System.Text.RegularExpressions.Regex.Match(chList.Total.ToString(), searchString);
                        if (m.Success) searchList.Add(chList);
                    }
                    
                }
            }
            GridView1.EmptyDataText = "Search result is Nothing...";
            GridView1.DataSource = (searchString==String.Empty)?listCustHist:searchList; //if query string is empty display all records
            //else display search results
            //else no data found for search will be displayed.
            GridView1.DataBind();
        }

        public class CustomerOrdersHistory
        {
            public string ProductName { set; get; }
            public int Total { get; set; }
        }

        void Build_CustOrderHistResult_Data()
        {
            if (listCustHist == null) listCustHist = new List<CustomerOrdersHistory>();
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Aniseed Syrup ", Total = 6 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Chartreuse verte", Total = 21 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Escargots de Bourgogne", Total = 40 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Flotemysost", Total=20 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Grandma's Boysenberry Spread", Total = 16 });
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Lakkalikööri", Total=15});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Original Frankfurter grüne Soße", Total=2});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Raclette Courdavault", Total=15});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Rössle Sauerkraut", Total=17});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Spegesild", Total=2});
            listCustHist.Add(new CustomerOrdersHistory { ProductName = @"Vegie-spread", Total=20});
        }
        

    }
}