3

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
  • Why not use a GridVIew? That is a table in html. Commented Sep 19, 2017 at 19:11
  • I also tried gridView but that also didnt work, maybe i was referencing the class and id incorrectly Commented Sep 19, 2017 at 19:14

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

how would I reference the table id and class, if that is just the rows?
Sorry, I don't quite get what you mean. You can set the class with CssClass in the GridView. And rows with RowStyle-CssClass
0

I found this that also explained that i needed <thread> tags which i was missing.

Apply Jquery DataTables plugin to ASP GridView

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.