Thursday, 18 June 2015

How to sort data in gridview by clicking column header

In this article I am going to show how to sort Gridview Data in Ascending and Desending oreder by clicking on Column Header with the up and Down icons in header.

For this firstly you need to bind Gridview with a Datasource. Set allowsorting property true and set sortexpression property to to respective datafield name.
Here is the Html Code for the GirdView.

<asp:GridView ID="grd1" runat="server" Width="100%" BorderColor="#CFDDEE" BorderWidth="1px" BorderStyle="Solid"
        Font-Names="Verdana,Geneva,sans-serif" Font-Size="11px"
        AutoGenerateColumns="False" onsorting="grd1_Sorting" AllowSorting="true"
        onrowdatabound="grd1_RowDataBound">
<Columns>
    <asp:BoundField DataField="ID" HeaderText=" User ID">
    </asp:BoundField>
    <asp:BoundField DataField="User_Title" HeaderText="User Title" SortExpression="User_Title">
    </asp:BoundField>
    <asp:BoundField DataField="Role" HeaderText="Role" SortExpression="Role">
    </asp:BoundField>
    <asp:BoundField DataField="User_Name" HeaderText="User Name" SortExpression="User_Name">
    </asp:BoundField>
</Columns>
</asp:GridView>

Create Public Property of SortDirection type and store direction in ViewState.
    public SortDirection dir
    {
        get
        {
            if (ViewState["dirState"] == null)
            {
                ViewState["dirState"] = SortDirection.Descending;
            }
            return (SortDirection)ViewState["dirState"];
        }
        set
        {
            ViewState["dirState"] = value;
        }

    }

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
             ViewState["SortDirection"] = "Desc";
            gvDetails.DataSource = BindGridView();
            gvDetails.DataBind();
        }

    }
private DataTable BindGridView()
    {
        DataTable dtGrid = new DataTable();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        string strSelect = "SELECT ID,User_Name,User_Title,Role FROM User_Master_Tbl";
        SqlCommand cmd = new SqlCommand(strSelect, con);
        SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
        dAdapter.Fill(dtGrid);
        Session["DataTable"] = dtGrid;
        return dtGrid;
    }
protected void grd1_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dt = new DataTable();
        dt = (DataTable)Session["DataTable"];
        string sortingDirection = string.Empty;
        if (dir == SortDirection.Ascending)
        {
            dir = SortDirection.Descending;
            sortingDirection = "Desc";
        }
        else
        {
            dir = SortDirection.Ascending;
            sortingDirection = "Asc";
        }
        DataView sortedView = new DataView(dt);
        sortedView.Sort = e.SortExpression + " " + sortingDirection;
        ViewState["SortDirection"] = sortingDirection;
        grd1.DataSource = sortedView;
        grd1.DataBind();
    }
protected void grd1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string imgAsc = @" <img src='image/AscArrow.png' border='0' title='Ascending' />";
        string imgDes = @" <img src='image/DscArrow.png' border='0' title='Descending' />";
        if (e.Row.RowType == DataControlRowType.Header)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                LinkButton lnkbtn = (LinkButton)e.Row.Cells[i].Controls[0];
                {
                    if (ViewState["SortDirection"] != null)
                    {
                        if (ViewState["SortDirection"].ToString() == "Asc")
                        {
                            lnkbtn.Text += imgAsc;
                        }
                        else
                            lnkbtn.Text += imgDes;
                    }
                    else
                    {
                        lnkbtn.Text += imgDes;
                    }
                }
            }
        }
    }
Here are the Up/Down icons:

Hope this will help you.

No comments:

Post a Comment