Apply Jquery DataTables plugin to ASP GridView
You can add thead
, tbody
and tfoot
tags using GridView Prerender event try this code
protected void GridView1_PreRender(object sender, EventArgs e) {
// You only need the following 2 lines of code if you are not
// using an ObjectDataSource of SqlDataSource
GridView1.DataSource = Sample.GetData();
GridView1.DataBind();
if (GridView1.Rows.Count > 0) {
//This replaces <td> with <th> and adds the scope attribute
GridView1.UseAccessibleHeader = true;
//This will add the <thead> and <tbody> elements
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
//This adds the <tfoot> element.
//Remove if you don't have a footer row
GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
Don't forget to add the event handler on source page as below
<asp:GridView ID="GridView1" runat="server" CssClass="gvv"
OnPreRender="GridView1_PreRender">
</asp:GridView>
Now you can simply call JQuery function as usual to render it
$(document).ready(function () {
$(".gvv").dataTable();
});
The problem is that GridView control doesn't add <thead>
element but just put the header row into <body>
section of generated table whereas the Data Table plugin requires a <thead>
section in a table. Try to use following script:
$(function () {
$(".gvv").prepend( $("<thead></thead>").append( $(this).find("tr:first") ) ).dataTable();
});
P.S. also you can use controls those don't rendering with default layout like Repeater or ListView
Please try below code.