Tuesday, April 16, 2013

jquery datatable row grouping plugin

Here in this post i will show how to group rows using Jquery DataTable Plugin.
This plugin was provided by third party vendor for DataTables, but the link provided was not working so i decided to show how to use it... in this post... for more examples U can refer 

http://www.datatables.net/extras/

Out Put :













ASPX Page :



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Grouping.aspx.cs" Inherits="DT_Pagination.Grouping" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <%--<link href="media_ColVis/css/ColVisAlt.css" rel="stylesheet" type="text/css" />--%>
    <link href="media_ColVis/css/ColVis.css" rel="stylesheet" type="text/css" />
    <link href="media/css/TableTools.css" rel="stylesheet" type="text/css" />
    <link href="media/css/TableTools_JUI.css" rel="stylesheet" type="text/css" />
    <link href="Scripts/css/demo_table_jui.css" rel="stylesheet" type="text/css" />
    <link href="Scripts/css/themes/overcast/jquery.ui.theme.css" rel="stylesheet" type="text/css" />
    <link href="Scripts/css/themes/overcast/jquery-ui.css" rel="stylesheet" type="text/css" />
    <link href="Scripts/css/jquery.dataTables_themeroller.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/js/jquery.js" type="text/javascript"></script>
    <script src="Scripts/js/jquery.dataTables.min.js" type="text/javascript"></script>
    <script src="media/js/ZeroClipboard.js" type="text/javascript"></script>
    <%--<script src="media/js/TableTools.min.js" type="text/javascript"></script>--%>
    <script src="media/js/TableTools.js" type="text/javascript"></script>
    <script src="Scripts/js/jquery.dataTables.columnFilter.js" type="text/javascript"></script>
    <script src="Scripts/js/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
    <script src="Scripts/js/FixedHeader.js" type="text/javascript"></script>
    <script src="media_ColVis/js/ColVis.js" type="text/javascript"></script>
    <script src="Scripts/js/jquery.dataTables.rowGrouping.js" type="text/javascript"></script>
    <style type="text/css">
        .ui-datepicker-calendar tr.ui-datepicker-calendar td.ui-datepicker-calendar td a.ui-datepicker-calendar th
        {
            font-sizeinherit;
        }
        div.ui-datepicker
        {
            font-size10px;
        }
        .ui-datepicker-title span
        {
            font-size10px;
        }
        
        .my-style-class input[type=text]
        {
            colorgreen;
        }
    </style>
    <script type="text/javascript">
        var oTable;
        $(document).ready(function () {
            $.datepicker.regional[""].dateFormat = 'dd/mm/yy';
            $.datepicker.setDefaults($.datepicker.regional['']);
 
            TableTools.DEFAULTS.aButtons = [
       "copy""csv""xls""pdf""print",
       {
           "sExtends""collection",
           "sButtonText""Save",
           "aButtons": [
                                                "csv",
                                                "xls",
           //"pdf",
                                                {
                                                "sExtends""pdf",
                                                //"sPdfOrientation": "landscape",
                                                "sPdfMessage""Your custom message would go here."
                                            },
                                                "print"
                                            ]
       }]
 
            //TableTools.DEFAULTS.aButtons = [ "copy", "csv", "xls",  "pdf" ];
 
 
 
            /*          Main Functionality       */
 
            $('#GridView1').dataTable({
                //"oLanguage": { "sSearch": "Search the nominees:" },
                "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                "iDisplayLength": 10,
                "aaSorting": [[0, "asc"]],
                "bJQueryUI"true,
                "bAutoWidth"false,
                "bProcessing"true,
                "sDom"'<"top"i><"title">lt<"bottom"pf>',
                "sPaginationType""full_numbers",
                "bRetrieve"true,
 
                //Scrolling--------------
                "sScrollY""350px",
                "sScrollX""100%",
                "sScrollXInner""100%",
                "bScrollCollapse"true,
 
                // ----  Print_Export_Copy  ----                
                "sDom"'T<"clear"><"H"lfr>t<"F"ip>',
                //"sDom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>',                            
 
                /*
                // ----- Column Visiblity ------ 
                //                "aoColumnDefs": [{ "bVisible": false, "aTargets": [2]}],
                //                "sDom": '<"H"Cfr>t<"F"ip>',
                //                //"sDom": 'C<"clear">lfrtip',
                //                //"sDom": '<"H"fr>tC<"F"ip>',   
                "sDom": 'TC<"clear">lfrtip',
                //"sDom": 'R<"H"Cfr>t<"F"ip>',
                //"sDom": '<"top"i>rt<"bottom"flp><"clear">',
                //"sDom":'<"H"lfr>t<"F"ip>',
                //"sDom": '<"H"lCfr>t<"F"ip>', 
                "oColVis":
                {
                "sDom": 'C<"clear">lfrtip',
                "activate": "mouseover",
                "bJQueryUI": true,
                "bRestore": true,
                "aiExclude": [0],
                "buttonText": "<b>&nbsp;Change Columns&nbsp;&nbsp;</b>" //Show / hide columns
                },
                // -- End Of ColVis
                */
 
 
                //--- Dynamic Language---------
                "oLanguage": {
                    "sZeroRecords""There are no Records that match your search critera",
                    "sLengthMenu""Display _MENU_ records per page&nbsp;&nbsp;",
                    "sInfo""Displaying _START_ to _END_ of _TOTAL_ records",
                    "sInfoEmpty""Showing 0 to 0 of 0 records",
                    "sInfoFiltered""(filtered from _MAX_ total records)",
                    "sEmptyTable"'No Rows to Display.....!',
                    "sSearch""Search all columns:"
                },
 
                /* Column Sorting And Searching */
                //                "aoColumns": [
                //        { "bSearchable": false }, //Disable search on this column 1
                //        {"bSortable": false }, //Disable sorting on this column 2               
                //        {"asSorting": ["asc"] }, //Allow only "asc" sorting on column 2
                //        null,
                //        { "sSortDataType": "dom-text", "sType": "numeric" },
                //        { "iDataSort": 4 }, //Use column 4 to perform sorting
                //        null,
                //        null
                //        ],
 
 
                /*  Column Visibilities */
                //    "aoColumns": [
                //                /* Sno */{"bSearchable": false, "bVisible": false},
                //       /* Engine */   null,
                //       /* Browser */  null,
                //       /* Platform */ { "bSearchable": false, "bVisible":    false },
                //       /* Version */  { "bSearchable": false, "bVisible":    false },
                //                /* Grade */     null,
                //                            /* Share */    null,
                //                            /* Date */    null
                //      ],
 
                "oSearch": {
                    "sSearch""",
                    "bRegex"false,
                    "bSmart"true
                },
 
                //------------------------Total in footer                
                "fnFooterCallback"function TotalCalc(nRow, aaData, iStart, iEnd, aiDisplay) {
                    /* Calculate the total market share for all browsers in this table (ie inc. outside the pagination) */
                    var iTotalMarket = 0;
                    for (var i = 0; i < aaData.length; i++) {
                        //alert('Length : ' + aaData.length + ', Row No : ' + i + ', Share : ' + aaData[i][6]);
                        iTotalMarket += parseInt(aaData[i][4]);
                    }
 
                    /* Calculate the market share for browsers on this page */
                    var iPageMarket = 0;
                    for (var i = iStart; i < iEnd; i++) {
                        iPageMarket += parseInt(aaData[aiDisplay[i]][4]);
                        //alert('Length : ' + iStart + ', Row No : ' + i + ', Share : ' + aaData[aiDisplay[i]][6] + 'Total : ' + iPageMarket);
                    }
 
                    /* Modify the footer row to match what we want */
                    var nCells = nRow.getElementsByTagName('td');
                    nCells[0].innerHTML = 'Total : ' + parseInt(iPageMarket * 100) / 100 +
    '% (' + parseInt(iTotalMarket * 100) / 100 + '% Grand Total)';
                } // End of Footer Footer
                //////////////////////////////////////  Row Grouping............................................. ///////////////////////////
            }).rowGrouping({
                iGroupingColumnIndex: 1
                //, bHideGroupingColumn: false
                //,sGroupingColumnSortDirection: "asc"
                , iGroupingOrderByColumnIndex: 0
            });
 
            // ------- Header Buttons -----------
            $('<a id="btnDelete" style="padding: 0px; display:none;" class="ui-button ui-widget ui-state-default ui-corner-all'
            + 'ui-button-text-only" href="javascript:void(0)"><span style="font-size: small; padding: 2px 5px;"'
            + 'class="ui-button-text"> Delete selected Row</span></a>&nbsp;&nbsp;<button id="refresh">Refresh</button>').appendTo('div.dataTables_length');
            //$('<button id="refresh">Refresh</button>').appendTo('div.dataTables_length'); //ReFresh Button
 
 
            /*
            $("table#GridView1").dataTable().columnFilter(
            {
            //sPlaceHolder: "foot:before",
            "aoColumns": [
            null, //{ "type": "number-range" },
            {"type": "text", width: "50px" },
            { "type": "select" },
            { "type": "text" }, //null, //{ "type": "date-range", width: "50px" },
            {"type": "number-range", width: "50px" },                                  
            { "type": "date-range"}   //{ "type": "date-range", width: "50px" },
            ]
            });
            */
 
            // -------------  Fixed Header   -------------
            //            oTable = $('#GridView1').dataTable();
            //            new FixedHeader(oTable);
 
            //$('#GridView1 div.title').text("This is a table title");
 
            /* Add a click handler to the rows - this could be used as a callback */
            $("#GridView1 tbody tr").click(function (e) {
                if ($(this).hasClass('row_selected')) {
                    $(this).removeClass('row_selected');
                    $('#btnDelete').hide();
                }
                else {
                    oTable.$('tr.row_selected').removeClass('row_selected');
                    $(this).addClass('row_selected');
                    $('#btnDelete').show();
                }
            });
 
            /* Add a click handler for the delete row */
            $('#btnDelete').click(function () {
                var anSelected = fnGetSelected(oTable);
                if (anSelected.length !== 0) {
                    /* Nedd Ajax Call To perform in serverSide*/
                    if (confirm('Are you sure you wish to delete this row?')) {
                        /* do the delete */
                        oTable.fnDeleteRow(anSelected[0]);
                    }
                    else {
                        $("#GridView1 tbody tr").removeClass('row_selected');
                        $('#btnDelete').hide();
                    }
                }
            });
 
            $.fn.dataTableExt.oStdClasses["filterColumn"] = "my-style-class";
 
            $('#GridView1 tbody td').click(function () {
                /* Get the position of the current data from the node */
                var aPos = oTable.fnGetPosition(this);
                var aData = oTable.fnGetData(aPos[0]);
                //alert(aData[0]);
            });
 
            /* Init the table */
            oTable = $('#GridView1').dataTable();
        });
 
        function fnGetSelected(oTableLocal) {
            return oTableLocal.$('tr.row_selected');
        }
        //$("div.tools").html('Organize by: <select id="booking_status"><option value="">All Bookings</option><option value="confirmed">Upcoming</option><option value="arrived">Arrived</option><option value="rejected">Rejected</option></select>');
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="Shadow" style="width880pxpadding5px;">
        <asp:GridView ID="GridView1" runat="server" OnPreRender="GridView1_PreRender" ShowFooter="true"
            AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound" >
            <Columns>
                <asp:TemplateField HeaderText="S.No">
                    <ItemTemplate>
                        <%# Eval("id"%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Engine">
                    <ItemTemplate>
                        <%# Eval("engine")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Browser">
                    <ItemTemplate>
                        <%# Eval("browser")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Platform">
                    <ItemTemplate>
                       <asp:Label ID="lblPlatform" runat="server" Text='<%# Eval("platform")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Grade">
                    <ItemTemplate>
                        <asp:Label ID="lblGrade" runat="server" Text='<%# Eval("grade")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Market Share(%)">
                    <ItemTemplate>
                        <%# Eval("marketshare")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Date">
                    <ItemTemplate>
                        <%# Eval("RDate")%>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html> 


Code Behind :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
 
namespace DT_Pagination
{
    public partial class Grouping : System.Web.UI.Page
    {
        string strConnect = "server=.\\MYDATABASE; user id=sa; pwd=malathi; database=aspdotnetDB;";
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                DataSet dataset = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter("select *,convert(varchar(10),released,103) as RDate from ajax", strConnect);
                da.Fill(dataset, "ajax");
 
                SqlDataAdapter da1 = new SqlDataAdapter("select * from ajax", strConnect);
                da1.Fill(dataset, "ajax1");
 
 
                //dataset.Tables.Add(dt.Copy());
                GridView1.DataSource = dataset.Tables[0];
                GridView1.DataBind();
            }
            catch (Exception ex)
            {
                string ErrMsg = ex.Message;
                int lineNo = ExceptionHelper.LineNumber(ex);
            }
        }
 
        protected void GridView1_PreRender(object sender, EventArgs e)
        {
            GridView1.UseAccessibleHeader = false;
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
            GridView1.FooterRow.TableSection = TableRowSection.TableFooter;            
        }
 
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //e.Row.Cells[2].ColumnSpan = 2;
                //e.Row.Cells[3].Style.Add("display", "none");                
                //e.Row.Cells[2].Text = "PlotForm , Grade";
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //string platform = ((Label)e.Row.FindControl("lblPlatform")).Text;
                //string Grade = ((Label)e.Row.FindControl("lblGrade")).Text;
                //e.Row.Cells[2].ColumnSpan = 2;
                //e.Row.Cells[3].Style.Add("display", "none");
                //e.Row.Cells[3].Text = "";
                //((Label)e.Row.FindControl("lblPlatform")).Text = platform + ", <b>Grade :</b> " + Grade;
            }
        }        
    }
}

DownLoad the Code from HERE

No comments:

Post a Comment