Gridview sorting ascending descending image example

Today i want to share Gridview ascending/descending image example with all of you.

To see sorting example visit my previous articles. How to enter ascending/descending image direction in gridview header? is common question for beginners. So, i have prepare one example to show you how you will do this.

In aspx page declare grid view as follow.

                        <%# Eval("BusinessEntityID")%>
                        First Name
                        <%# Eval("FirstName") %>
                        Last Name
                        <%# Eval("LastName") %>
                        <%# Eval("AddressLine1") %>
                        <%# Eval("City") %>
                        Postal Code
                        <%# Eval("PostalCode") %>

Now, in cs file add following code at BindData function which is done all job for you. We are adding few lines which is search Linkbutton from gridview Hearder and add image at that place.

            // For Sorting Image
            LinkButton lnkID = (LinkButton)this.gvData.HeaderRow.FindControl("lnkID");
            LinkButton lnkFirstName = (LinkButton)this.gvData.HeaderRow.FindControl("lnkFirstName");

            if (this.gvData_SortBy == lnkID.CommandArgument.ToLower())
            else if (this.gvData_SortBy == lnkFirstName.CommandArgument.ToLower())

Add one more function to insert image in header.

    protected void InsertSortImage(TableCell orderedCell)
        string imgUrl = null;

        if (this.gvData_IsAsc == true)
            imgUrl = "images/desc.gif";
            imgUrl = "images/asc.gif";

        Image img = new Image();
        img.ImageUrl = imgUrl;
        img.BorderStyle = BorderStyle.None;

Now, you are ready just add “Images” folder in your project and add two images asc.gif and desc.gif. I am attaching both images here with this article.