ASP.NET c# gridview SortExpression SortDirection w/ manually binding data

Posted on 2007-10-17
Last Modified: 2013-12-17
Gridview properties SortExpression and SortDirection not maintaining values when using paging...

1) I am manually binding to a MySQL database
2) Therefore I am manually handling the firing of the Paging and the Sorting events in codebehind.
3) I do a sort on Column.  It sorts fine...
4) I click on say Page 4.. The sorting is completely lost but goes to page 4 of the default sorting (as if the page was loaded the first time and no sort was indicated)

I don't understand why the gridview maintains the PageIndex Value and not the SortExpression and SortDirection values when posting back...For example, if I click on Page 4 and then click a new column to sort.  The GridView.pageIndex holds it value.

But if I click on a column header for sorting and then click on page 4.  The gridview.sortdirection and gridview.sortexpression are reset....

<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" />
        <asp:UpdatePanel ID="upEmployeeList" runat="server" UpdateMode="conditional" EnableViewState="true">
            <asp:GridView cellpadding=5 ID="gvEmployeeList" runat="server"
                AutoGenerateColumns="false" PageSize="20" AllowSorting="true" AllowPaging="true"
                    <asp:BoundField DataField="EmpId" HeaderText="Emp ID" SortExpression="EmpId" ReadOnly="true" />
                    <asp:BoundField DataField="Last_Name" HeaderText="Last Name" SortExpression="Last_Name" ReadOnly="true" />
                    <asp:BoundField DataField="First_Name" HeaderText="First Name" SortExpression="First_Name" ReadOnly="true" />
                    <asp:BoundField DataField="Manager" HeaderText="Manager" SortExpression="Manager" ReadOnly="true" />
                    <asp:BoundField DataField="Division" HeaderText="Division" SortExpression="Division" ReadOnly="true" />
                    <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" ReadOnly="true" />
                    <asp:BoundField DataField="Floor" HeaderText="Floor" SortExpression="Floor" ReadOnly="true" />
                    <asp:ButtonField ImageUrl="~/admin/images/grid_edit.gif" CommandName="edit" ButtonType="Image" />
                    <asp:ButtonField ImageUrl="~/admin/images/grid_delete.gif" CommandName="delete" ButtonType="Image" />
                <HeaderStyle CssClass="gridHeader"  />
                <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Left" VerticalAlign="Middle" />
                <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
                <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
                <AlternatingRowStyle BackColor="#F7F7F7" HorizontalAlign="Left" VerticalAlign="Middle" />
c# file
    private string sSortDirection="ASC";
    private string sSortExpression="EmpId";

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            gvEmployeeList.DataSource = ds_gvEmployeeList();
    protected DataSet ds_gvEmployeeList()
        string sSQL = "SELECT a.*,  CONCAT(b.Last_Name,', ',b.First_Name) as Manager, d.NAME as Division, c.NAME as Department ";
        sSQL = sSQL + " from employee a ";
        sSQL = sSQL + " LEFT JOIN Employee b ON a.MGRID=b.EmpID ";
        sSQL = sSQL + " LEFT JOIN Department c ON a.DEPTID=c.DEPTID ";
        sSQL = sSQL + " LEFT JOIN Division d ON a.DVSNID=d.DVSNID ";
        sSQL = sSQL + " ORDER BY " + sSortExpression + " " + sSortDirection;

        DataSet dsTemp = new DataSet();
        using (OleDbDataAdapter da_gvEmployeeList = new OleDbDataAdapter(sSQL, sConnect)){
            da_gvEmployeeList.Fill(dsTemp, "EmployeeList");
        return dsTemp;
    protected void gvEmployeeList_PageIndexChanging(Object sender, GridViewPageEventArgs e)
        gvEmployeeList.PageIndex = e.NewPageIndex;
        gvEmployeeList.DataSource = ds_gvEmployeeList();
    private string GetSortDirection(string sSortDirection){
        switch (sSortDirection)
            case "ASC":
                return "DESC";
            case "DESC":
                return "ASC";
                return "ASC";
    protected void gvEmployeeList_Sorting(Object sender, GridViewSortEventArgs e)
        sSortDirection = GetSortDirection(e.SortDirection.ToString());
        sSortExpression = e.SortExpression;
        gvEmployeeList.DataSource = ds_gvEmployeeList();

any help is greatly appreciated!

Yours in deepest gratitude,

Angela Law

Question by:angelalaw
    LVL 96

    Accepted Solution

    It doesn't look like you are persisting those values after post-back.


    Author Comment

    Hi bob,

    Thanks for answering, I truly appreciate it...I take it you mean storing them in the viewstate or the session state separately?

    What I do not understand is that the Gridview.pageindex persists within the control without any need for outside storage elsewhere when doing postbacks.

    Why is this not happening for the SortExpression and SortDirection of the grid view.  I did EnableViewState for the gridview.  So shouldn't that persist through that control without the need to store it in an outside location.

    I have gotten around the problem by storing it in the ViewState area.  But I really like to understand WHY and if I did something wrong? the gridView.pageindex value persists within the gridview  control on postbacks automatically so why doesn't sortdirection and sortexpression is not persisting in the gridview control.

    Anyone have any explanations?
    LVL 96

    Expert Comment

    by:Bob Learned
    That is just the nature of the beast.


    Author Comment

    Is there a way to know what properties will persist through the control when enableviewstate is set to true?

    Many thanks again :)

    Angela Law
    LVL 96

    Expert Comment

    by:Bob Learned

    I don't use the GridView anymore, I use the Telerik RadGrid, so it is difficult to answer that question with any certainty.


    Author Comment

    ah okay,

    thank you for your time :)


    Expert Comment

    For sorting, you has two options to do

    1) You can use Order by in Query SQL. It's what you are doing

    2) You also use DataView to sort.
       a) Once you get DataSet from the Query as ds
       b) You do as the following
                 DataView dataView = ds.Tables[0].DefaultView;
                 string sFilter = ..... / You sort whatever you want
                 dataView.RowFilter = sFilter;
                 // After that, you use DataView to bind to DataGrid or DataView
                 dg1.DataSource = dataView;

    I hope it's helpful for you.


    Sin Le

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    6 Surprising Benefits of Threat Intelligence

    All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

    This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
    Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now