How to sort GridView?

Specifying Sorting Attributes For GridView

To enable sorting for GridView set Sorting attribute for the control to True and if you are specifying event handlers for controls on page itself then set the event handler function for OnSort event of the control. The following code snippet from ASPX page shows how these attributes are set.
<sp:GridView ID="ctlGridView" runat="server" autogeneratecolumns=False 
    OnRowCreated="OnRowCreated" allowpaging="True"
    allowsorting="True" onsorting="OnSort">
    <columns>
        <asp:boundfield datafield="ProductID" sortexpression="ProductID" />
        <asp:boundfield datafield="Name" headertext="Name" sortexpression="Name" />
        <asp:boundfield datafield="ProductNumber" headertext="Product Number" sortexpression="ProductNumber" />
   </columns>
</asp:GridView>      
       

OnSort Event Handler

Now when grid is loaded and user clicks on column header, OnSort event gets fired and your handler will get called. Second parameter for event handler is GridViewSortEventArgs which has two properties that specify sort direction and sort expression for the column which was clicked by user. These properties are SortExpression and SortDirection. Unfortunately in all my attempts I have always seen value of SortDirection property set to Ascending. So only piece of useful information we have is SortExpression. You can use this property for multiple purposes. One basic purpose is to sort the data table with this sort expression. You can append ASC or DESC to sort expression to sort data as per user's click action. And then you can save this sort expression in ViewState to decide if SortDirection needs to be reversed on next click on header. You can compare SortExpression from the event argument with the one stored in ViewState. If they are different that means a new sort command needs to be executed otherwise you simply need to change SortDirection.

Showing Image In Column To Indicate Sort Direction

Displaying an image indicator along side the column header to show sort direction gives a very cleat indication to user about which column is sorted and in what direction. Header is nothing more than a collection of controls. To display an indicator image you simply need to insert appropriate image at desired location. If you look at the image shown at the top of the article, you will notice that "Name" column has been sorted in ascending order an arrow image is shown right next to column header. Following code snippet shows the implemenation included in the sample project of this article.
protected void OnSort(object sender, GridViewSortEventArgs e)
{
    // There seems to be a bug in GridView sorting implementation. Value of
    // SortDirection is always set to "Ascending". Now we will have to play
    // little trick here to switch the direction ourselves.
    if (String.Empty != m_strSortExp)
    {
        if (String.Compare(e.SortExpression, m_strSortExp, true) == 0)
        {
            m_SortDirection = 
                (m_SortDirection == SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
        }
    }
    ViewState["_Direction_"] = m_SortDirection;
    ViewState["_SortExp_"] = m_strSortExp = e.SortExpression;
    this.bindGridView();
}       
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        if (String.Empty != m_strSortExp)
        {
            AddSortImage(e.Row);
        }
    }
}
void AddSortImage(GridViewRow headerRow)
{
    Int32 iCol = GetSortColumnIndex(m_strSortExp);
    if (-1 == iCol)
    {
        return;
    }
    // Create the sorting image based on the sort direction.
    Image sortImage = new Image();
    if (SortDirection.Ascending == m_SortDirection)
    {
        sortImage.ImageUrl = "~/dwn.gif";
        sortImage.AlternateText = "Ascending Order";
    }
    else
    {
        sortImage.ImageUrl = "~/up.gif";
        sortImage.AlternateText = "Descending Order";
    }

    // Add the image to the appropriate header cell.
    headerRow.Cells[iCol].Controls.Add(sortImage);
}
       

0 comments:

Post a Comment