Pages

Thursday, May 24, 2012

Scrollable GridView with Fixed Headers and Client Side Sorting using jQuery in ASP.Net


This was asked to me lot of times but I couldn’t find a better way of doing it hence did not write. Few days back I noticed that a plug in is available for jQuery that can sort HTML tables Thus I quickly tried to merge it with my Scrollable GridView and finally succeeded and here’s it for you an ASP.Net GridView Control with Fixed Headers and scroll functionality with Client Side sorting.
 
GridView Markup
Below is the GridView Markup
<div id = "container" style ="height:200px;overflow:auto;width:617px ">
<asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns = "false" CssClass = "grid">
   <Columns>
    <asp:BoundField ItemStyle-Width = "200px"
    DataField = "CustomerID" HeaderText = "CustomerId" />
    <asp:BoundField ItemStyle-Width = "200px"
    DataField = "City" HeaderText = "City"/>
    <asp:BoundField ItemStyle-Width = "200px"
    DataField = "Country" HeaderText = "Country"/>
   </Columns>
</asp:GridView>
</div>

You will notice above I have placed the GridView inside a DIV of fixed height and width and setting its overflow property to auto so that the scrollbars are available. Also I have set the width of the Div slightly more than the GridView so that the horizontal scrollbar is hidden and it can accommodate the vertical scrollbar.
 
Binding the GridView
Below are the methods to Bind the GridView control with data
C#
private void BindGrid()
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("select * from customers");
    cmd.Connection = con;
    sda.SelectCommand = cmd;
    sda.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    GridView1.HeaderRow.Attributes["style"] = "display:none";
    GridView1.UseAccessibleHeader = true;
    GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}

VB.Net
Private Sub BindGrid()
 Dim dt As New DataTable()
 Dim strConnString As [String] = System.Configuration.ConfigurationManager _
                    .ConnectionStrings("conString").ConnectionString
 Dim con As New SqlConnection(strConnString)
 Dim sda As New SqlDataAdapter()
 Dim cmd As New SqlCommand("select * from customers")
 cmd.Connection = con
 sda.SelectCommand = cmd
 sda.Fill(dt)
 GridView1.DataSource = dt
 GridView1.DataBind()
 GridView1.HeaderRow.Attributes("style") = "display:none"
 GridView1.UseAccessibleHeader = True
 GridView1.HeaderRow.TableSection = TableRowSection.TableHeader
End Sub

Above after binding the GridView I am hiding the GridView header row by setting its display to none. If you set ShowHeader to false it will break the working of sorting library. In the next statements I am modifying the GridView settings so that it renders with THEAD and TBODY tags which are necessary for the library in order to sort a table
 
Building the Dummy Header
For preparing the dummy header we will need to extract the header row of the GridView as shown in the screenshot
ScrollableGridViewwith sorting.png
Now complete paste it above the GridView and remove display:none so that the dummy header is visible, I have also provided ID to the dummy header table and your dummyHeader and the scrollable GridView is ready
ScrollableGridViewwith sorting2.png
CSS
Add the following CSS to the head section of the page
<style type = "text/css">
    .sortAsc
    {
        background-imageurl(images/asc.gif);
        background-repeatno-repeat;
        background-positioncenter right;
        cursorpointer;
        width:200px;
    }
    .sortDesc
    {
        background-imageurl(images/desc.gif);
        background-repeatno-repeat;
        background-positioncenter right;
        cursorpointer;
        width:200px;
    }
    .grid
    {
        font-family:Arial;
        font-size:10pt;
        width:600px
    }
    .grid THEAD
    {
         background-color:Green;
         color:White;
    }
</style>
 
Client Side Sorting
Now for the Client Side Script I have used the tablesorter jQuery Plugin which will be used to sort the GridView control. Hence add the following scripts to your page
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    $(document).ready(function() {
    $("#<%=GridView1.ClientID%>").tablesorter();
        SetDefaultSortOrder();
    });
 
    function Sort(cell, sortOrder) {
        var sorting = [[cell.cellIndex, sortOrder]];
        $("#<%=GridView1.ClientID%>").trigger("sorton", [sorting]);
        if (sortOrder == 0) {
            sortOrder = 1;
            cell.className = "sortDesc";
        }
        else {
            sortOrder = 0;
            cell.className = "sortAsc";
        }
        cell.setAttribute("onclick""Sort(this, " + sortOrder + ")");
        cell.onclick = function() { Sort(this, sortOrder); };
        document.getElementById("container").scrollTop = 0;
    }
 
    function SetDefaultSortOrder() {
        var gvHeader = document.getElementById("dummyHeader");
        var headers = gvHeader.getElementsByTagName("TH");
        for (var i = 0; i < headers.length; i++) {
            headers[i].setAttribute("onclick""Sort(this, 1)");
            headers[i].onclick = function() { Sort(this, 1); };
            headers[i].className = "sortDesc";
        }
    }
</script>

All the client side methods are explained below
The following method notifies the tablesorter library the ID of the control that needs to be sorted and also calls theSetDefaultSortOrder method to set the default sort order.
    $(document).ready(function() {
    $("#<%=GridView1.ClientID%>").tablesorter();
        SetDefaultSortOrder();
    });
 
The following function as the name suggests sets the default sort order for the GridView in the dummy header that we’ve created earlier
function SetDefaultSortOrder() {
        var gvHeader = document.getElementById("dummyHeader");
        var headers = gvHeader.getElementsByTagName("TH");
        for (var i = 0; i < headers.length; i++) {
            headers[i].setAttribute("onclick""Sort(this, 1)");
            headers[i].onclick = function() { Sort(this, 1); };
            headers[i].className = "sortDesc";
        }
}
 
This function get’s called when user clicks on the header row for sorting it accepts the cell and the sort order in which the grid needs to be sorted.
function Sort(cell, sortOrder) {
        var sorting = [[cell.cellIndex, sortOrder]];
        $("#<%=GridView1.ClientID%>").trigger("sorton", [sorting]);
        if (sortOrder == 0) {
            sortOrder = 1;
            cell.className = "sortDesc";
        }
        else {
            sortOrder = 0;
            cell.className = "sortAsc";
        }
        cell.setAttribute("onclick""Sort(this, " + sortOrder + ")");
        cell.onclick = function() { Sort(this, sortOrder); };
        document.getElementById("container").scrollTop = 0;
}
 
Checkout the demo GridView below
CustomerIdCityCountry
ALFKIBerlinGermany
ANATRMéxico D.F.Mexico
ANTONMéxico D.F.Mexico
AROUTLondonUK
BERGSLuleåSweden
BLAUSMannheimGermany
BLONPStrasbourgFrance
BOLIDMadridSpain
BONAPMarseilleFrance
BOTTMTsawassenCanada
BSBEVLondonUK
CACTUBuenos AiresArgentina
CENTCMéxico D.F.Mexico
CHOPSBernSwitzerland
COMMISao PauloBrazil
CONSHLondonUK
DRACDAachenGermany
DUMONNantesFrance
EASTCLondonUK
ERNSHGrazAustria
FAMIASao PauloBrazil
FISSAMadridSpain
FOLIGLilleFrance
FOLKOBräckeSweden
FRANKMünchenGermany
FRANRNantesFrance
FRANSTorinoItaly
FURIBLisboaPortugal
GALEDBarcelonaSpain
GODOSSevillaSpain
GOURLCampinasBrazil
GREALEugeneUSA
GROSRCaracasVenezuela
HANARRio de JaneiroBrazil
HILAASan CristóbalVenezuela
HUNGCElginUSA
HUNGOCorkIreland
ISLATCowesUK
KOENEBrandenburgGermany
LACORVersaillesFrance
LAMAIToulouseFrance
LAUGBVancouverCanada
LAZYKWalla WallaUSA
LEHMSFrankfurt a.M.Germany
LETSSSan FranciscoUSA
LILASBarquisimetoVenezuela
LINODI. de MargaritaVenezuela
LONEPPortlandUSA
MAGAABergamoItaly
MAISDBruxellesBelgium
MEREPMontréalCanada
MORGKLeipzigGermany
NORTSLondonUK
OCEANBuenos AiresArgentina
OLDWOAnchorageUSA
OTTIKKölnGermany
PARISParisFrance
PERICMéxico D.F.Mexico
PICCOSalzburgAustria
PRINILisboaPortugal
QUEDERio de JaneiroBrazil
QUEENSao PauloBrazil
QUICKCunewaldeGermany
RANCHBuenos AiresArgentina
RATTCAlbuquerqueUSA
REGGCReggio EmiliaItaly
RICARRio de JaneiroBrazil
RICSUGenèveSwitzerland
ROMEYMadridSpain
SANTGStavernNorway
SAVEABoiseUSA
SEVESLondonUK
SIMOBKobenhavnDenmark
SPECDParisFrance
SPLIRLanderUSA
SUPRDCharleroiBelgium
THEBIPortlandUSA
THECRButteUSA
TOMSPMünsterGermany
TORTUMéxico D.F.Mexico
TRADHSao PauloBrazil
TRAIHKirklandUSA
VAFFEÅrhusDenmark
VICTELyonFrance
VINETReimsFrance
WANDKStuttgartGermany
WARTHOuluFinland
WELLIResendeBrazil
WHITCSeattleUSA
WILMKHelsinkiFinland
WOLZAWarszawaPoland

The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari  Opera 
* All browser logos displayed above are property of their respective owners.

That’s it with this the article comes to an end. Hope you liked it.
You can download the complete source code in VB.Net and C# using the link below
ScrollableGridViewWithFixedHeadersAndSorting.zip

No comments:

Post a Comment