Thursday 28 March 2013

Filter GridView as you type (ASP.NET C# with jQuery)


Filter GridView as you type (ASP.NET C# with jQuery)

I’ve often found that our client’s web portals have way too much data on screen, so here’s a quick and easy “Filter as you type” JavaScript/jQuery block:
function SetupFilter(textboxID, gridID, columnName) {
    $('#' + textboxID).keyup(function () {
        var index;
        var text = $("#" + textboxID).val();
 
        $('#' + gridID + ' tbody tr').each(function () {
            $(this).children('th').each(function () {
                if ($(this).html() == columnName)
                    index = $(this).index();
            });
 
            $(this).children('td').each(function () {
                if ($(this).index() == index) {
                    var tdText = $(this).children(0).html() == null ? $(this).html() : $(this).children(0).html();
 
                    if (tdText.indexOf(text, 0) > -1) {
                        $(this).closest('tr').show();
                    } else {
                        $(this).closest('tr').hide();
                    }
                };
            });
        });
    });
};
Then all you need to do, after you include the above code segment in your page head or startup .js file is to call the below for each textbox you want to actively filter your grid:
$(function () { SetupFilter("myTextBox", "myGridView", "My Column Name"); });
Just make sure you reference your controls with the correct ID. By using ClientIDMode=”Static” you can ensure it’s the same ID as you defined it in the ASP.NET markup.
<asp:TextBox ID="myTextBox" runat="server" ClientIDMode="Static" />
 
<asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="False" ClientIDMode="Static"
ShowHeaderWhenEmpty="True">
    <Columns>
        <asp:BoundField DataField="one" HeaderText="My first column" />
        <asp:BoundField DataField="two" HeaderText="My Column Name" />
    </Columns>
</asp:GridView>
You can even include the textbox as template fields in the grid header.
Make sure you are making use of jQuery libraries in order for this to work.


https://skydrive.live.com/?cid=95767ce97c6d84e3&id=95767CE97C6D84E3%21261&authkey=!AMYiYGhg8NRJnDM



4 comments:

  1. Hi. I love this. I don't understand much of the jscript code, but I know how to copy and paste it. And this does exactly what I'm trying to achieve in a simple interface.

    I wonder though, is there a way to make it search in several columns at the same time?

    ReplyDelete
  2. Thanks so much for this cool and simple coding! It works wonderful for me! Appreciated :)

    ReplyDelete
  3. thanks you men, realy you help me,

    ReplyDelete