Search, Sort in gridview using C#.Net, Ajax and jQuery

In this article, I will show you how to search in Gridview by using SqlDataSource’s FilterParameters and Sort by using jQuery tablesorter plugin.

Step:1 Create Searchbox and Gridview
Create asp:textbox called txtSearch to search data.
then create a simple Gridview called Gridview1 with TemplateFields for the fields that you would like to search for. Here I created a Two TemplateField for my two search fields, First Name and Last Name. The other point of interest is that the Eval statement for these 2 fields is wrapped around a function that we’re going to write called HighlightText which is use to highlight search text.

 
<asp:ScriptManager ID="ScriptManager" runat="server" />
      Search: <asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged"  />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" >
        <ContentTemplate>
            
            <div class="GridviewDiv">
           
                 <asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                    AllowSorting="true" DataSourceID="dsGridview" Width="540px" PageSize="10" CssClass="yui">
                    <Columns>
                        <asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" ItemStyle-Width="40px"
                            ItemStyle-HorizontalAlign="Center" />
                        <asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
                            <ItemStyle Width="120px" HorizontalAlign="Left" />
                            <ItemTemplate>
                                <asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("FirstName").ToString()) %>' runat="server"
                                    CssClass="TextField" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
                            <ItemStyle Width="120px" HorizontalAlign="Left" />
                            <ItemTemplate>
                                <asp:Label ID="lblLastname" Text='<%# HighlightText(Eval("LastName").ToString()) %>' runat="server"
                                    CssClass="TextField" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department"
                            ItemStyle-Width="130px" />
                        <asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location"
                            ItemStyle-Width="130px" />
                    </Columns>
                </asp:GridView>
                </div>
        </ContentTemplate>
         <Triggers>
                <asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
            </Triggers>
    </asp:UpdatePanel>

Note that in above code, I put gridview1 into asp:updatePanel and set trigger to refresh UpdatePanel (Gridview1) when txtSearch value changed. Please do not put txtSearch into UpdatePanel.

Step 2: Create a datasource with a FilterExpression
In order to enable our search functionality, add a FilterExpression to the datasource. The FilterExpression that I’m using checks for the first name and last name against the txtSearch Text box.

 
 <asp:SqlDataSource ID="dsGridview" runat="server" ConnectionString="<%$ ConnectionStrings:TempConnectionString %>"
        SelectCommand="SELECT * FROM [Employees]" FilterExpression="firstname like '%{0}%' or lastname like '%{1}%'">
        <FilterParameters>
            <asp:ControlParameter Name="firstname" ControlID="txtSearch" PropertyName="Text" />
            <asp:ControlParameter Name="lastname" ControlID="txtSearch" PropertyName="Text" />
        </FilterParameters>
    </asp:SqlDataSource>

Step 3: CodeBehind C#
Basically every time we’re displaying the First and Last name data in our Gridview, we check to see if there is any search text, and if there is, use a regular expression to enclose the search string in a CSS span which turns the text yellow.

 
   string SearchString = "";
    protected void Page_Load(object sender, EventArgs e)
    {
txtSearch.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + txtSearch.ClientID.Replace("_", "$") + "\\',\\'\\')', 0);");
        if (!IsPostBack)
        {
            Gridview1.DataBind();
        }
    }
    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
         SearchString = txtSearch.Text;
    }
    public string HighlightText(string InputTxt)
    {
        string Search_Str = txtSearch.Text.ToString();
        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
        // Highlight keywords by calling the 
        //delegate each time a keyword is found.
        return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
        // Set the RegExp to null.
        RegExp = null;
    }
    public string ReplaceKeyWords(Match m)
    {
        return "<span class=highlight>" + m.Value + "</span>";
    }

Important: txtSearch_TextChanged event will not fire until you press enter. But to do a fast and easy search just typing in the textbox without havig to push any button or ‘enter’ to get the result back using AJAX updatepanel need to use Onkeyup event. just add this line to the Page_Load:

 
    txtSearch.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + txtSearch.ClientID.Replace("_", "$") + "\\',\\'\\')', 0);");

Step 4: Add the CSS class for highlighting

Step 5: Sorting Gridview
I’m using jQuery tableSorter plugin to sort gridvew. you can download from here.

 
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript" src="http://ashishblog.com/ash/source/jquery.tablesorter-2.0.3.js"></script>
  <link type="text/css" rel="stylesheet" href="http://ashishblog.com/ash/source/style.css" />
  <script type="text/javascript">
     jQuery(document).ready(function () {
         $("#Gridview1").tablesorter({ debug: false, widgets: ['zebra'], sortList: [[0, 0]] });
     });
</script>

Thanks.

42 responses to “Search, Sort in gridview using C#.Net, Ajax and jQuery”

  1. can we download this

    it will work ?? see the error

    Error 1 The type or namespace name ‘Match’ could not be found (are you missing a using directive or an assembly reference?)
    Default2.aspx.cs 42 35

  2. hello there..nice info..but i have one problem..where do i add the CSS class for highlighting? i already have css class but when i added it, it doesn’t work..

    file : css/style.css

    .highlight {
    text-decoration: none;
    color:black;
    background:yellow;
    }

    is it need to be added at different place since you used code like this :
    .highlight {text-decoration: none;color:black;background:yellow;}

    thanks in advance! :)

  3. oh yea! 1 more thing i wanna ask you..
    how about i want to create more than two column for searching?

    SelectCommand=”SELECT [Nama_Pelajar], [Tingkatan], [Sesi], [Isu] FROM [Form]” FilterExpression=”Nama_Pelajar like ‘%{0}%’ or Tingkatan like ‘%{1}%’ or Sesi like ‘%{2}%’ or Isu like ‘%{3}%'”>

    could you help me to fix this code because im so noob with coding..=(

  4. For me it only works if i put the line Gridview1.DataBind(); outside of if(!IsPostBack) condition, what could be happening??

  5. but ashish it is not working textbox’s onkeyup.
    updatepanel is not refreshing..
    i do as u suggessted… it is working on pressing ‘enter’ key only. kindly suggest.

  6. hi Vish,

    u can change the code to:

    txtSearch.Attributes.Add(“onkeyup”, “__doPostBack(\’ctl00$” + txtSearch.ClientID.Replace(“_”, “$”) + “\’,\’\’)”);

    i got itfixed on my project.

  7. Ashish thanks for this awesome example, however I have a question since I’m a noob to programming. What would you add to the code behind if you had another textbox along with the original to do a search, lets say one textbox is lastname and the other is address. What would you need to add for it to work. Could you please point me in the right direction.

    THanks

    Paul

  8. Hello,

    good example i have tried it but i got following error(line no 17)
    Input string was not in a correct format.
    Line 15: if (!IsPostBack)
    Line 16: {
    Line 17: Gridview1.DataBind();
    Line 18: }
    Line 19: }

  9. hello sbs,

    your suggestion and this tutorial doesn’t work me, however i have full walk through of this code but still i m no able to see record blinking in textbox as this tutorial state. Kindly suggest me to get run this code for my project as well. I have been facing same problem as mr. vish do.

    Thanks!!

  10. @sbs: txtSearch.Attributes.Add(“onkeyup”, “__doPostBack(\’ctl00$” + txtSearch.ClientID.Replace(“_”, “$”) + “\’,\’\’)”);

    ths works g00d

  11. @Ashish sir, please wait for a moment i just email you the text file containing faulty code. i guess, problem may be due to version changing and not due to syntax. i do use vs2010 c#4.0

    thanks

  12. @Ashish sir,

    actually i have caught my mistake now my code is running so smoothly… and i have noticed a thing this search technique doesn’t work on 3 letters immediately. Hope you will find some time to remove this confusion.

    Thank you!!

  13. Hello Ashish,
    Many Thanks for sharing this wonderful work.
    I have one issue the I am not sure how to deal with.
    When I search for a name and get for example three pages of data, One i navigate to the secod page my grid turns to the full query result. I there a way that I can only navigate through the 3 pages I searched?

    Many Thanks

  14. this is alternative code for the Attribute.Add() that worked for me since the above one was not working.
    txtSearch.Attributes.Add(“onkeyup”, string.Format(“javascript:__doPostBack(‘{0}’,”)”, this.txtSearch.ClientID));
    thank you for the code you really got me out of a jam’

  15. Dear
    I converted this code in VB, I am facing below error. I am not good in programming as well.

    ************************************
    Compilation Error
    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: BC32008: Delegate ‘System.Text.RegularExpressions.MatchEvaluator’ requires an ‘AddressOf’ expression or lambda expression as the only argument to its constructor.

    Source Error:

    Line 22: ‘ Highlight keywords by calling the
    Line 23: ‘delegate each time a keyword is found.
    Line 24: Return RegExp.Replace(InputTxt, New MatchEvaluator(ReplaceKeyW))
    Line 25: ‘ Set the RegExp to null.
    Line 26: RegExp = Nothing

    ****************************************
    error appearing against Line # 24 “ReplaceKeyW”
    I will very thankful to you for your support.
    kind regards
    Ali

  16. Dear Ashish!
    I fix this problem, I used (AddressOf ReplaceKeyWords) instead of (RepalceKeyWords).
    anyways thanks for your support & really above article is very good & helpful.
    —>
    one small question, I want to use multiple text boxes with option buttons & controls. e.g EMP ID, Name etc
    can you give me some hints.
    take care
    regards
    Ali

  17. Hi !Your post is very helpful , but when i tried to run, it throws http exception showing that “firstname” property doesnot exist . My Database consist of ID,firstname,designation and I wanted to use “firstname” feild for search purpose .Can you help me with this problem, and also is it compatible with detailsview too ?

  18. Hello sir can i use this search textbox without data source Because i wanna Bind gridview in code behind. How can i do this?

  19. Thanks for this post.
    textbox’s onkeyup is nt working
    updatepanel is not refreshing..
    i do as u suggessted… it is working on pressing ‘enter’ key only. kindly suggest.?

  20. Hi Ashish ,
    This post is very useful to learn jquery with gridview.
    Is there any place that i can download the entire code to check. when i try to implement this into my project, after typing in textbox character its loading and not searching the records inside the gridview.
    Kindly send me the entire code to reframe my code.

    Regards,
    Gawaskar.

  21. thanks..i love ur post…it helps me alot..

    i m struct in searching modulw.
    my query is:
    i want searching module like tally.
    eg.
    suppose their is textbox,when we start to type character it will automatically find by like

    operator in database table and the result should display in listbox in c#.net.

Leave a Reply to Ali Mukhtar