ASP.NET - Sorting GridView - Javascript - Asked By Anandh Ramanujam on 03-Feb-11 09:39 AM

HI,

I want to sort the gridview using javascript...
And also want to include Image in the Column Header to indicate for order of sorting 
Can anybody help me in this regard

Thanks.
Jatin Prajapati replied to Anandh Ramanujam on 03-Feb-11 09:53 AM
Hi Anandh,
Here is your answer.

1 Design grid view like this:

 

<asp:GridView ID="gvResults" runat="server" AutoGenerateColumns="false" AllowSorting="true"  EmptyDataText="Results not found.">

          <Columns>

<asp:TemplateField ItemStyle-Width="8%">

              <HeaderStyle VerticalAlign="Middle" CssClass="headPad" />

              <HeaderTemplate>

                <asp:LinkButton ID="lnkUserID" Width="100%" Height="100%" runat="server" meta:resourcekey="lnkUserID" OnDataBinding="Sort">

                  User ID &nbsp;<asp:Image ID="imgSort1" runat="server" SkinID="ImgSortDesc"  Visible="true" ImageAlign="AbsMiddle" /></asp:LinkButton>

              </HeaderTemplate>

              <ItemTemplate>

                <asp:Label ID="lblUid" runat="server"

Text='<%#DataBinder.Eval(Container.DataItem,"UserID")%>'></asp:Label>

              </ItemTemplate>

            </asp:TemplateField>

      <asp:TemplateField ItemStyle-Width="15%">

              <HeaderStyle VerticalAlign="Middle" CssClass="headPad" />

              <HeaderTemplate>

                <asp:LinkButton ID="lnkUserName" runat="server" Width="100%" Height="100%" meta:resourcekey="lnkUserName"

                  OnDataBinding="Sort">

                  User Name&nbsp;<asp:Image ID="imgSort2" runat="server" CssClass="hidden" SkinID="ImgSortDesc"

                    Visible="true" ImageAlign="AbsMiddle" />

                </asp:LinkButton>

              </HeaderTemplate>

              <ItemTemplate>

                <asp:Label ID="lblUname" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"UserName")%>'>

                </asp:Label></ItemTemplate>

            </asp:TemplateField>

            <asp:TemplateField ItemStyle-Width="15%">

              <HeaderStyle VerticalAlign="Middle" CssClass="headPad" />

              <HeaderTemplate>

                <asp:LinkButton ID="lnkName" runat="server" Width="100%" Height="100%" meta:resourcekey="lnkName"

                  OnDataBinding="Sort">

                  Name&nbsp;<asp:Image ID="imgSort3" runat="server" CssClass="hidden" SkinID="ImgSortDesc"

                    Visible="true" ImageAlign="AbsMiddle" />

                </asp:LinkButton></HeaderTemplate>

              <ItemTemplate>

                <asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Name")%>'>

                </asp:Label></ItemTemplate>

            </asp:TemplateField>

</Columns>

        </asp:GridView>

 

 

In Grid View, Header Template, I have taken Link button and I'm calling “Sort” method in “OnDataBinding” to do sorting. And I used image control to show image sort direction. And I will be calling “Sort” methods for all link buttons.

 

2. Java Scripts:

<script type="text/javascript" language="javascript">

var a; // array ref

var ASC = true; //bool for ASC og DESC sort

var col; // the column to be sorted

var rowStart = 1;

var ascImg = '';

var descImg = '';

function sort(sortCol,tableID,maxCol,imgName)

{

   

      try

      {      

           

            a = new Array();

            table = document.getElementById(tableID);

            y = table.getElementsByTagName('tr').length-1;

        //put all tr in an array

            for(x=rowStart;x<=y;x++)

            {                   

                  a.push(table.rows[x]);

            }

            //ensure that sorting will be done ASC if sortcolumn changes

            if(col != sortCol)

            {

              col = sortCol;

               

            }

             //just calling sort

             

            a.sort(Sort);

             

            //changes between ASC and DESC sort order

            if(ASC)

              {

              ASC = false;

              }

            else

              ASC = true;

            //code for displaying sort image starts here

             

             

            var imgID ="";

             if(ASC == true)

      {      

      

        for(j=0;j<=maxCol;j++)

        {            

           

           imgID = tableID+imgName+j;

          

               var objImg = document.getElementById(imgID);

              

               if(objImg != null)

               {

                objImg.style.visibility = "hidden";

               }

             

        }

         

          imgID = tableID+imgName+sortCol;

        

        var objImg = document.getElementById(imgID);

         if(objImg != null)

         {

          objImg.style.visibility = "visible";

          objImg.src = descImg;

         }

             

      }

          else

          {   

                                      

         for(j=0;j<=maxCol;j++)

            {              

              

                imgID = tableID+imgName+j;

              

                   var objImg = document.getElementById(imgID);

                   if(objImg != null)

                   {

                    objImg.style.visibility = "hidden";

                   }                  

            }

            

          imgID = tableID+imgName+sortCol;

        

            var objImg = document.getElementById(imgID);

             if(objImg != null)

             {

              objImg.style.visibility = "visible";

              objImg.src = ascImg;

             }

          }

           

           

 

        //code for displaying sort image Ends here

         

        

            //just calling updaterTable

             

            updateTable(rowStart);

      }

      catch(e)

      {

        

      }

}

 

//sorts numericly or letters

function Sort(h,l)

{

  try

  {

   

    if(h.getElementsByTagName('span')[col] != null && l.getElementsByTagName('span')[col] != null)

    {

         

          var dateH = new Date(h.getElementsByTagName('span')[col].innerHTML.toLowerCase());

              var dateL = new Date(l.getElementsByTagName('span')[col].innerHTML.toLowerCase());

                   

        if(ASC)

        {

                   

              if(!validNumber(h.getElementsByTagName('span')[col].innerHTML) || !validNumber(l.getElementsByTagName('span')[col].innerHTML) )

              {    

                         

                    if (h.getElementsByTagName('span')[col].innerHTML.toLowerCase() < l.getElementsByTagName('span')[col].innerHTML.toLowerCase()) sortValue=-1;

                    else if (h.getElementsByTagName('span')[col].innerHTML.toLowerCase() > l.getElementsByTagName('span')[col].innerHTML.toLowerCase()) sortValue=1;

                    else sortValue=0;

                         

                         

                    if(dateH !="NAN" && dateL !="NAN")

                    {

                          if(dateH < dateL) sortValue=-1

                          else if(dateH > dateL) sortValue=1

                    }    

                         

                    return sortValue;

                               

              }

                   

              return h.getElementsByTagName('span')[col].innerHTML - l.getElementsByTagName('span')[col].innerHTML

        }

        else

        {

              if(!validNumber(h.getElementsByTagName('span')[col].innerHTML) || !validNumber(l.getElementsByTagName('span')[col].innerHTML) )

              {    

                         

                    if (h.getElementsByTagName('span')[col].innerHTML.toLowerCase() > l.getElementsByTagName('span')[col].innerHTML.toLowerCase()) sortValue=-1;

                    else if (h.getElementsByTagName('span')[col].innerHTML.toLowerCase() < l.getElementsByTagName('span')[col].innerHTML.toLowerCase()) sortValue=1;

                    else sortValue=0;

                         

                    if(dateH !="NAN" && dateL !="NAN")

                    {

                               

                          if(dateH > dateL) sortValue=-1

                          else if(dateH < dateL) sortValue=1

                    }    

                         

                    return sortValue;  

              }

               

              return l.getElementsByTagName('span')[col].innerHTML -  h.getElementsByTagName('span')[col].innerHTML

        }

        }

        return 0;

       }

       catch(e)

       {

       

       }

}

</script>

 

 

 

 

 

 

3. C# Code .cs file:

 

int  colNumber=0; //class level member

 

public void Sort(object sender, System.EventArgs e)

  {

    // add javascript eventhandler to columnheader    

    ((LinkButton)sender).Attributes.Add("onclick", "sort('" + colNumber + "','" + gvResults.ClientID + "','3','_ctl01_imgSort'); return false;");

    colNumber++;

 

  }

 

Here, I am calling java script sort method  and my parameters would be. colNumber which alwasys starts with '0',grid view client id, and the number of link buttons I have, and the image id.

Anandh Ramanujam replied to Jatin Prajapati on 03-Feb-11 09:59 AM
Thanks a lot..

but i couldnt find 'updateTable' function....

P Patel replied to Anandh Ramanujam on 03-Feb-11 10:25 AM
Below blog post explains how to do this more simply using jquery.

http://beckelman.net/demos/jqueryTableSorterConPaging/default.aspx


http://beckelman.net/demos/jqueryTableSorterConPaging/default.aspx

http://beckelman.net/demos/jQueryTableSorterSortedColumnHighlighting/Default.aspx

http://beckelman.net/post/2008/11/20/jQuery-tableSorter-and-quickSearch-Plugins-Together-Demo.aspx

Anoop S replied to Anandh Ramanujam on 03-Feb-11 10:43 AM

Try the http://jquery.com/ plugin http://tablesorter.com/

<script type="text/javascript" src="/path/to/jquery-latest.js"></script>
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>
 
....
 
<script type="text/javascript">
  var aspxElements = {
    theGrid: '<%= myGrid.ClientID %>' //I'm not entierly sure this is the id of the table or some container element
  };
 
  $(document).ready(function() {
    $('#' + aspxElements.theGrid).tablesorter();
  });
</script>

demo on this http://tablesorter.com/docs/#Demo