Wednesday, November 25, 2015

tablesorter - A sort-able HTML table with JQuery plugin for ASP.Net GridView Control

When displaying information, such as a table in HTML, it is always better if an additional features can be provided in a way that the users can filter on client side without posting back. The benefits is that its faster as it processes on client side and it has rich contents which is able to filter as well as sort columns.
The following example will show how it can be applied to ASP.Net GridView Control.

1. Create your own GridView with the following properties.
 ClientIDMode="Static" OnDataBound="grdMyGrid_DataBound"   
This declaration must be needed to keep the id of the grid to be constant after rendered especially if there are any master pages.
The grdMyGrid_DataBound is important to set the header properties for the grid (table after rendered).

2. In code behind, add the following,
 protected void grdMyGrid_DataBound(object sender, EventArgs e)  
   {  
     if (grdMyGrid.Rows.Count > 0)  
     {  
       grdMyGrid.UseAccessibleHeader = true;  
       grdMyGrid.HeaderRow.TableSection = TableRowSection.TableHeader;  
     }  
   }  

3. Now you need to refer the tablesorter js and css files to the page.
 <link rel="stylesheet" href="style/TableSorter/theme.blue.css" type="text/css" />  
 <script src="script/TableSort/jquery.tablesorter.min.js" type="text/javascript"></script>  
 <script src=">script/TableSort/jquery.tablesorter.widgets.js" type="text/javascript"></script>  
* Also make sure the to add references to JQuery too.

4. Now the table sorter can applied as per below from the relevant page related JS file.
 $(document).ready(function () {  
 var $table = $('#grdMyGrid').tablesorter({  
       theme: 'blue', //The theme to be applied  
       widgets: ["zebra", "filter"],  
       widgetOptions: {  
         filter_hideFilters: false,          
         filter_external: '.search',  
         filter_placeholder: { search: 'Search...' }, //The Search field mask text  
         filter_saveFilters: false,  
         filter_reset: '.reset'  
       },  
       headers: {  
         5: { sorter: false, filter: false }, //Disable sorting and filtering  
         6: { sorter: false, filter: false } //Disable sorting and filtering  
       }  
     });  
 });  

5. The final result looks like below;


Read the documentation here:
http://tablesorter.com/docs/

Happy coding :)

No comments:

Post a Comment