3

I want to use "JQuery Datatable" with ASP.NET GridView.

I tried something i found, but it didn't work.

GridView -

<asp:GridView ID="gridViewTasks" runat="server" AutoGenerateColumns="false" CssClass="table table-striped table-bordered dt-responsive nowrap" Width="100%">
    <Columns>
        <asp:BoundField DataField="task_id" HeaderText="TaskID" Visible="false" />
        <asp:BoundField DataField="task_description" HeaderText="Task Name" />
        <asp:BoundField DataField="task_detail" HeaderText="Task Detail" Visible="false" />
        <asp:BoundField DataField="task_createdate" HeaderText="Create Date" />
        <asp:BoundField DataField="task_targetdate" HeaderText="Target Date" />
        <asp:BoundField DataField="task_isReaded" HeaderText="Task Read" Visible="false" />
        <asp:BoundField DataField="product_id" HeaderText="ProductID" Visible="false" />
        <asp:BoundField DataField="product_name" HeaderText="Product" />
        <asp:BoundField DataField="status_id" HeaderText="StatusID" Visible="false" />
        <asp:BoundField DataField="status_name" HeaderText="Status" />
        <asp:BoundField DataField="severity_id" HeaderText="SeverityID" Visible="false" />
        <asp:BoundField DataField="severity_name" HeaderText="Severity" />
        <asp:BoundField DataField="user_masterID" HeaderText="MasterID" Visible="false" />
        <asp:BoundField DataField="gorevi_veren" HeaderText="Master" />
        <asp:BoundField DataField="user_slaveID" HeaderText="SlaveID" Visible="false" />
        <asp:BoundField DataField="görevi_alan" HeaderText="Slave" />
        <asp:BoundField DataField="task_score" HeaderText="Score" />
    </Columns>
</asp:GridView>

JavaScript -

1

$(document).ready( function () {
$('#gridViewTasks').DataTable();} );

2

$(document).ready( function () {
$("#gridViewTasks").prepend( $("<thead></thead>").append( $(this).find("tr:first") ) ).DataTable() ;} );

Script And CSS i used -

<script src="jquery-1.9.1.min.js"></script>
<link href="jquery.dataTables.min.css" rel="stylesheet" />
<script src="jquery.dataTables.min.js"></script>

And also i tried girdView_PreRender Function

i am adding references in GridView when i use.

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
    gridViewTasks.DataSource = Sample.GetData();
    gridViewTasks.DataBind();

    if (gridViewTasks.Rows.Count > 0)
    {
        //This replaces <td> with <th> and adds the scope attribute
        gridViewTasks.UseAccessibleHeader = true;
        //This will add the <thead> and <tbody> elements
        gridViewTasks.HeaderRow.TableSection = TableRowSection.TableHeader;

        //This adds the <tfoot> element. 
        //Remove if you don't have a footer row
        gridViewTasks.FooterRow.TableSection = TableRowSection.TableFooter;

    }
}

Code Behind - i am using Linq to SQL

var sorgu = from gorev in db.Tasks
join ga in db.Users on gorev.user_slaveID equals ga.user_id
join gv in db.Users on gorev.user_masterID equals gv.user_id
join product in db.Products on gorev.product_id equals product.product_id
join severity in db.Severities on gorev.severity_id equals severity.severity_id
join status in db.Status on gorev.status_id equals status.status_id
select new
{
    gorev.task_id,
    gorev.task_description,
    gorev.task_detail,
    gorev.task_createdate,
    gorev.task_targetdate,
    gorev.task_isReaded,
    product.product_id,
    product.product_name,
    status.status_id,
    status.status_name,
    severity.severity_id,
    severity.severity_name,
    gorev.user_masterID,
    gorevi_veren = gv.user_username,
    gorev.user_slaveID,
    görevi_alan = ga.user_username,
    gorev.task_score                       
};

gridViewTasks.DataSource = sorgu;
gridViewTasks.DataBind();

So, How can i implement Jquery DataTable in ASP.NET GridView.

2 Answers 2

14

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>
Sign up to request clarification or add additional context in comments.

7 Comments

it worked.Thanks for your help. But , there are things i didn't understand exactly. Can you explain briefly ? 1-) What is the .ClientID ? Why we use it ? 2-) And why we use RowDataBound event ?
1) aspnet can rename the ID of a control on the clientside, so gridViewTasks could become PlaceHolder_GridView1. If that happens then $("#gridViewTasks")` will not work because that ID does not exist. Using ClientID will make sure you use the correct ID in the client side.
2) In this case the RowDataBound event is meant to add <thead> and <tbody> to the gridview, which is not present by default. It replaces your $("#gridViewTasks").prepend( $("<thead></thead>").append( $(this).find("tr:first"). But you could remove it if you wish to use the jQuery method to add them.
OK. Thank you so much. Finally, Do you know how i added Excell,Print etc. buttons in Jquery DataTable ? İf you know, can you share with me ?
Sorry, that I don't know.
|
2

Try this, It will work as per your need.

<div class="table-responsive">
    <asp:GridView ID="gvExample" runat="server">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                   <%-- Binding Expression--%>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Call necessary CSS(bootstrap.css, font-awesome.css..etc)

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" />

Call necessary scripts(bootstrap.js, jquery.js ..etc)

<!-- jQuery CDN - Slim version (=without AJAX) -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

<!-- Popper.JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>

<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

<!-- jQuery Data Tables CDN -->
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript" charset="utf8"></script>

<!-- Bootstrap Data Tables JS -->
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js" type="text/javascript" charset="utf8"></script>

then add this below script

 <script>
    $(document).ready(function () {
        $('#<%= gvExample.ClientID%>').prepend($("<thead></thead>").append($("#<%= gvExample.ClientID%>").find("tr:first"))).DataTable({
            stateSave: true,
        });
    });
</script>

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.