Searching Inside the GridView Control
By AzamSharp
Views: 10841



Introduction:


I was browsing the asp.net forums when I found a very interesting question. The question was how to search in a GridView control. If you think about it is a common practice to search the items in the database but when the items are already displayed in the GridView then why not search the GridView instead of making an expensive trip to the database. In this article I will demonstrate how to search in a GridView control.

Populating the GridView Control:

Before I begin the article I would like to thank Dimitrios Markatos for his article "Highlighting Search Keywords in a DataGrid Web Control" which formed the basic for this article.

Okay, let's begin with populating the GridView Control. The BindData method given below is used to populate the GridView.

 private void BindData()
    {
        string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
        SqlConnection myConnection = new SqlConnection(connectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT ProductID, ProductName FROM Products", myConnection);

        DataSet ds = new DataSet();
        ad.Fill(ds);

        GridView1.DataSource = ds;
        GridView1.DataBind();
    }



The above code uses the SqlDataAdapter to populate the DataSet and finally binds the DataSet to the GridView control.

Creating the Search Box:

The search box is no more then a simple TextBox. Check out the HTML code given below:

Enter Search String: <asp:TextBox ID="txtSearch" runat="server" />


Creating the HighlighText Method:

The next task is to create the HighlighText method which is responsible for highlighting the search text inside the GridView control.

protected string HighlightText(string searchWord,string inputText)
    {

        Regex expression = new Regex(searchWord.Replace(" ", "|"), RegexOptions.IgnoreCase);

        return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
    }


HighlighText takes two parameters which are searchWord and inputText. The searchWord is the text that we type in the search text box and the inputText contains the text which is being searched for the text. As, you can see in the above code that I am taking the help of the ReplaceKeywords method which is defined below:

 public string ReplaceKeywords(Match m)
    {
        return "<span class='highlight'>" + m.Value + "</span>";
    }



The ReplaceKeywords method appends a style to the searched text and returns it to the calling method.

Configuring the GridView Control:

The last thing that you need to do is to configure the GridView control so that it uses the HighlightText method. Take a look at the code below in which I have used the HighlightText method on the "Product Name" column. The searchString is a protected class level string variable which contains the searchText inputted by the user in the search TextBox.     


  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        
        <Columns>
        
        <asp:TemplateField HeaderText="Product Name">
        <ItemTemplate>
       <%# HighlightText(searchString, (string) Eval("ProductName")) %>
        </ItemTemplate>
        
        </asp:TemplateField>
        
        </Columns>
              
        
        </asp:GridView>


Now,run the application and type something in the search TextBox and press the search button. As, soon as you press the button the GridView "ProductName" column will be searched for the search keyword and if it finds the search word it highlights it using the "highlight" css class.




Happy programming!

UPDATE: Many users ask me that how they can persist the search results while the GridView is in paging mode. This can easily be accomplished and I have explained the solution in my blog entry. Please check out the post by clicking the link below:

http://aspadvice.com/blogs/azamsharp/archive/2006/11/09/Searching-in-GridView-With-Paging-Enabled.aspx


By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Help Required
Name: Shohin Keshwani
Date: 4/20/2007 1:57:47 AM
Comment:
Hey,
I have created a gridview in asp.net 2.0 using C#.. the problem i am facing is that, i have placed textbox in the grid.. now when the user will click on submit button, i wish to check the data in the textbox is valid or not, i.e, IsNumeric or not.
any suggestions

PS: I am Vb 6.0 developer by default and hence i specified the method IsNumeric. what we use in vb 6.0
Subject: IF you Can
Name: Mohammad
Date: 8/31/2007 7:27:17 AM
Comment:
hi iam mohammad
iam programmer from jordan if you can to send to me complete code of searching inside grid view because i try to write it when i saw it in your page but the code didnt work !
Subject: Fixing Positionof Header Row
Name: Ravi Lele
Date: 12/8/2007 1:39:13 AM
Comment:
Situation: I have placed a Gridview inside a fixed width panel, so that scrolling effect can be produced. PROBLEM: as i scroll it down the header row of the Gridview goes invisible, this is the problem. so i need to fix the position of the header row so that it should always remain viewable. I need your help in solving this.
Subject: DetailsView
Name: Patrick
Date: 3/8/2008 7:04:48 AM
Comment:
any info on the DetailsView - I trying to get multiple columns and having a hrad time w/ css freindly adapters..
Subject: Error occured
Name: darwin
Date: 3/24/2008 5:24:09 AM
Comment:
hey,
there is an error pointing at Match cant run the application
this is the error
The type or namespace name 'Match' could not be found (are you missing a using directive or an assembly reference?)
Subject: RE: Error Occured
Name: AzamSharp
Date: 3/25/2008 12:23:04 PM
Comment:
Hi Darwin, The Match class is contained inside the System.Text.RegularExpressions. Add the above namespace and you will be good to go!
Subject: Help
Name: Persis
Date: 4/23/2008 5:36:42 AM
Comment:
Hi, I need ur help now.It's nice to see ur code but i get the error saying ''System.Text.RegularExpressions.MatchEvaluator' is a delegate type and requires a single 'addressof' expression as the only argument to the constructor'. So what to do now. Thanks in Advance
Subject: Highlight Class
Name: AgnesLoyola
Date: 4/30/2008 6:07:53 AM
Comment:
I got the compilation error as The name 'searchString' does not exist in the current context.
Can anyone help me in clearing this error?
and also in creating the “highlight" css class.
Subject: Highlight Text
Name: Anand
Date: 5/8/2008 10:46:27 PM
Comment:
I got the compilation error as The name 'searchString' does not exist in the current context.
can anyone help plz.



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008