What I discovered is that the crux of the matter when attempting to layer jQuery DataTables over a GridView control is that you need to format the HTML of the GridView so that it's recognizable by the DataTables code. Essentially, your GridView needs to be formatted like so in order for it to be recognized:
<table> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table>
Here is what you can do at the very minimum to make this happen:
ASPX Page:
<script type="text/javascript" language="javascript" src="Scripts/jquery-1.10.2.js"></script> <script type="text/javascript" language="javascript" src="Scripts/jquery.datatables.min.js"></script> <link type="text/css" href="Content/jquery.dataTables.min.css" rel="stylesheet" /> <div class="row"> <div class="col-md-4"> <asp:GridView ID="GridView1" runat="server" CssClass="gvdatatable" AutoGenerateColumns="true" OnPreRender="GridView1_PreRender"> </asp:GridView> </div> </div> <script type="text/javascript"> $(document).ready(function () { $('.gvdatatable').dataTable({}); }); </script>
ASPX Page Code-Behind:
protected void Page_Load(object sender, EventArgs e) { } protected void GridView1_PreRender(object sender, EventArgs e) { GridView1.DataSource = GetData(); //GetData is your method that you will use to obtain the data you're populating the GridView with GridView1.DataBind(); if (GridView1.Rows.Count > 0) { //Replace the <td> with <th> and adds the scope attribute GridView1.UseAccessibleHeader = true; //Adds the <thead> and <tbody> elements required for DataTables to work GridView1.HeaderRow.TableSection = TableRowSection.TableHeader; //Adds the <tfoot> element required for DataTables to work GridView1.FooterRow.TableSection = TableRowSection.TableFooter; }
}
This code has been simplified from my original work, but I wanted to provide you with the bare bones minimum code that's needed so that you can get an idea of how to bolt this onto your existing project. Hope this helps!
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.