These few lines are all you need to get it working. You don’t need the prerender event. Just bind in Page_Load
in the IsPostBack
check. I did add a RowDataBound
event to the GridView
to add the <thead>
and <tbody>
sections programatically rather than with jQuery.
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>
<script type="text/javascript">
$(document).ready(function () {
$('#<%= GridView1.ClientID %>').DataTable();
});
</script>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
//check for a postback
if (!Page.IsPostBack)
{
//bind the gridview data
GridView1.DataSource = source;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is the header row
if (e.Row.RowType == DataControlRowType.Header)
{
//add the thead and tbody section programatically
e.Row.TableSection = TableRowSection.TableHeader;
}
}
UPDATE
If you are using a DataTable inside an UpdatePanel, use the following javascript to ensure proper binding after an Async PostBack.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
createDataTable();
});
createDataTable();
function createDataTable() {
$('#<%= GridView1.ClientID %>').DataTable();
}
</script>