Display SqlDataSource data in HTML table (DataTables Plugin)

Viewed 681

I want to display SQL Server data in a table <td> so I can use the plugin at https://datatables.net/ I am able to bind the data to things such as

<asp:PlaceHolder ID = "PlaceHolder1" runat="server" />

such as in this tutorial: https://www.aspsnippets.com/Articles/Display-data-from-database-in-HTML-table-in-ASPNet.aspx

However, the plugin needs a class and id from a table, and therefore doesn't work. I tried inserting class and id that the plugin needs like this but did not work

// Table start.
html.Append("<table border = '1'>");
html.Append("<table class = "display" id = "example">");

Is there a way of inserting a class and id to the table through html.append?

Thanks

2 Answers

If you have a GridView, you need to use the ClientID. Place the below GridView and JavaScript on the same aspx page.

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/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>

However, for a GridView to work with DataTables, you need to add a OnRowDataBound event. Then in code behind add the following code.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.TableSection = TableRowSection.TableHeader;
    }
}

This add the <thead> and <tbody> tags to the generated html, which is needed by datatables.net.

Related