Solved

Bi-Directional Sorting in Gridview

Posted on 2006-07-18
7
1,265 Views
Last Modified: 2008-05-19
Given the following Grid (and c# code), how do I set it up to sort Ascending AND Descending on Header-Click? (The idea is to click the header once to sort in one direction, and upon the grid reload, to set the sort direction to go the other way on the next click).

ASPX page:
<asp:GridView ID="grdvwActivityStmt" CssClass="idGrid" CellPadding="3"
    AutoGenerateColumns="false" runat="server" Width="100%"
    EmptyDataText="No Activity Statements on file."
    AllowPaging="true" AllowSorting="true"
    PageSize="100" OnPageIndexChanging="grdvwActivityStmt_PageIndexChanging"
    OnSorting ="grdvwActivityStmt_OnSorting" DataKeyNames="SSN" GridLines="None">
    <HeaderStyle CssClass="ItemHeader" />
    <RowStyle CssClass="Item" />
    <AlternatingRowStyle CssClass="AltItem" />
    <PagerSettings FirstPageText="&lt;&lt; First&#160;&#160;&#160;" LastPageText="&#160;&#160;&#160;Last &gt;&gt;" PreviousPageText="&#160;&lt; Prev&#160;" NextPageText="&#160;Next &gt;&#160;" Mode="NextPreviousFirstLast" Position="TopAndBottom" />
    <PagerStyle Font-Bold="True" BackColor="#FFFFFF" CssClass="BlackBold" HorizontalAlign="Center" BorderStyle="None" />
    <Columns>
        <asp:templatefield headertext="ST" SortExpression="DestinationState">
            <ItemStyle HorizontalAlign="Center" Width="10%" />
            <HeaderStyle HorizontalAlign="Center" />
            <itemtemplate>
                <%# DataBinder.Eval(Container.DataItem, "DestinationState") %>
            </itemtemplate>
        </asp:templatefield>
        <asp:templatefield headertext="Acknowledgement" SortExpression="HistoryCreateDate">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle Width="30%" />
            <itemtemplate>
                <%# DataBinder.Eval(Container.DataItem, "HistoryCreateDate") %>
            </itemtemplate>
        </asp:templatefield>
        <asp:templatefield headertext="EFIN" SortExpression="EFIN">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Center" Width="15%" />
            <itemtemplate>
                <%# DataBinder.Eval(Container.DataItem, "EFIN") %>
            </itemtemplate>
        </asp:templatefield>
    </Columns>
</asp:GridView>

ASPX.CS page:

    DataSet ds = new DataSet();
    DataView dv = new DataView();

#region Page Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            {
                dv = bindgrid(intAxaptaCustNum, strCustGUID);

                grdvwPgOne.DataSource = dv;
                grdvwPgOne.DataBind();
            }
    }
#endregion

#region Database Output Functions
    /// <summary>
    ///  Binding for the main gridView
    /// </summary>
    /// <returns></returns>
    private DataView bindgrid(string strAcctNum, string strCustGUID)
    {
        SqlConnection SQLConn = new SqlConnection(FCTaxContent.FCTaxContentConnectionString());
        SqlCommand sqlCmd = new SqlCommand("spx_GetInvoiceDataPageOne", SQLConn);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter sqlAdp = new SqlDataAdapter(sqlCmd);

        sqlCmd.Parameters.Add("@AcctNum", SqlDbType.VarChar);
        sqlCmd.Parameters["@AcctNum"].Value = strAcctNum;
        sqlCmd.Parameters.Add("@CustGUID", SqlDbType.VarChar);
        sqlCmd.Parameters["@CustGUID"].Value = strCustGUID;

        sqlAdp.Fill(ds);
        if (ViewState["sortExpr"] != null)
        {
            dv = new DataView(ds.Tables[0]);
            dv.Sort = (string)ViewState["sortExpr"];
        }
        else
        {
            dv = ds.Tables[0].DefaultView;
        }

        pnlActivityOutput.Visible = true;

        return dv;
    }

    /// <summary>
    ///  Sorting for the Header clicks in the main gridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grdvwPgOne_OnSorting(Object sender, GridViewSortEventArgs e)
    {
        if (e.SortDirection == SortDirection.Ascending)
        {
            ViewState["sortExpr"] = e.SortExpression;
        }
        else
        {
            ViewState["sortExpr"] = string.Concat(e.SortExpression, " ", SortDirection.Descending);
        }

        grdvwPgOne.DataSource = bindgrid(Session["AxaptaCustomerNumber"].ToString(), Session["AxaptaCustGUID"].ToString());
        grdvwPgOne.DataBind();

        pnlActivityOutput.Visible = true;
    }

    /// <summary>
    ///  Paging handler for the main gridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grdvwPgOne_PageIndexChanging(Object sender, GridViewPageEventArgs e)
    {
        grdvwPgOne.PageIndex = e.NewPageIndex;
        grdvwPgOne.DataSource = bindgrid(Session["AxaptaCustomerNumber"].ToString(), Session["AxaptaCustGUID"].ToString());
        grdvwPgOne.DataBind();

        pnlActivityOutput.Visible = true;
    }
#endregion


I'd give more points if there was a way, as this one has stumped me for quite some time.
0
Comment
Question by:Paul Kahl
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 12

Expert Comment

by:topdog770
ID: 17132021
I'm sure I'm missing something, but..

Why not store which direction the grid was sorted by last time and do the opposite direction next time the user asks for a sort?
0
 
LVL 3

Author Comment

by:Paul Kahl
ID: 17132279
Store it how? Session based? The idea is NOT to pass it through the query string. I want to prevent users (or abusers, really) from hacking urls and doing what they want, so I'd like to keep it in code.
0
 
LVL 12

Expert Comment

by:topdog770
ID: 17132307
Yeah.. i admit I was thinking session based....

Another option would be to create your own derived DataGrid class and allow sorting logic to be handled with the object itself..

benefits would include not having to rely on outside source of control or information to determine control behavior.. ie session variable and or parameter and redundantly, cleaner implementation with the exact functionality you are wanting.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Author Comment

by:Paul Kahl
ID: 17132398
That's already what I'm doing, actually. I have a built-in sort functionality in the grdvwPgOne_OnSorting function, but I can't get it to switch directions.
0
 
LVL 12

Accepted Solution

by:
topdog770 earned 500 total points
ID: 17132649
The grdvwPgOne_OnSorting function doesn't appear to try and change anything in terms of direction though or look at which direction was used to sort the last time into the function.. it just looks at the direction passed into the function and sorts in the specified direction.

It looks like you would need to call the grdvwPgOne_OnSorting from another function and manipulate the e.SortDirection argument to make any change.

thinking very simply... and not as complete snippet, I was thinking something like this

 protected void grdvwPgOne_OnSorting(Object sender, GridViewSortEventArgs e)
    {
        if( Session["LastSortDirection"].ToString() == "asc" )
        {
            ViewState["sortExpr"] = string.Concat(e.SortExpression, " ", SortDirection.Descending);
            Session["LastSortDirection"] = "desc";
        }
       else
      {  // default to ascending order if session variable not set...
            Session["LastSortDirection"] = "asc";
            ViewState["sortExpr"] = e.SortExpression;
     }

        grdvwPgOne.DataSource = bindgrid(Session["AxaptaCustomerNumber"].ToString(), Session["AxaptaCustGUID"].ToString());
        grdvwPgOne.DataBind();

        pnlActivityOutput.Visible = true;
    }
0
 
LVL 3

Author Comment

by:Paul Kahl
ID: 17132884
By jove, I think you've got it!

Here's the finished version, with detection for the object of session content.

protected void grdvwPgOne_OnSorting(Object sender, GridViewSortEventArgs e)
    {
        object objSortDir = Session["LastSortDirection"];
        if (!(objSortDir is object))
        {
            Session["LastSortDirection"] = "asc";
            ViewState["sortExpr"] = e.SortExpression;
        }
        else
        {
            if (Session["LastSortDirection"].ToString() == "asc")
            {
                ViewState["sortExpr"] = string.Concat(e.SortExpression, " desc");
                Session["LastSortDirection"] = "desc";
            }
            else
            {
                Session["LastSortDirection"] = "asc";
                ViewState["sortExpr"] = e.SortExpression;
            }
        }

        grdvwPgOne.DataSource = bindgrid(Session["AxaptaCustomerNumber"].ToString(), Session["AxaptaCustGUID"].ToString());
        grdvwPgOne.DataBind();

        pnlPg1.Visible = true;
    }
0
 
LVL 12

Expert Comment

by:topdog770
ID: 17132928
Cool!
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

636 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