Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8457841
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T12:54:55+00:00 2026-06-10T12:54:55+00:00

I have this grid view, it has 2 problems. if I sort it by

  • 0

I have this grid view, it has 2 problems.

  1. if I sort it by clicking on a column, and then I click again, its not sorted in des order.
  2. If once I sort with a col A and then click on any other column its not sorted again?

      <asp:GridView ID="grdReport" runat="server" AutoGenerateColumns="False" DataKeyNames="CustCode"
    ShowFooter="True" EmptyDataText="No record found" PageSize="50"
    CssClass="mGrid" onrowdatabound="grdReport_RowDataBound"
    AllowSorting="True" onsorting="grdReport_Sorting">
    <Columns>
       <asp:TemplateField HeaderText="Select">
            <ItemTemplate>
                <asp:CheckBox ID="chkSelect" runat="server"/>
            </ItemTemplate>
       </asp:TemplateField>
    
       <asp:TemplateField Visible="false">
       <ItemTemplate>
       <asp:Label ID="lblCustCodes" runat="server" Text='<%# Eval("CustCode") %>' CssClass="grdCustName"></asp:Label>
       </ItemTemplate>
       </asp:TemplateField>
    
      <asp:TemplateField HeaderText="Customer" SortExpression="Customer">
      <ItemTemplate>
       <asp:HyperLink Target="_blank" Text='<%# Eval("CustomerName") %>' runat="server" ID="hplNavigate">
       </asp:HyperLink>
       </ItemTemplate>
       </asp:TemplateField>
        <asp:BoundField DataField="QTY" HeaderText="Booked Qty" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"
            SortExpression="QTY">
            <FooterStyle HorizontalAlign="Right" />
            <ItemStyle HorizontalAlign="Right"></ItemStyle>
        </asp:BoundField>
           <asp:BoundField DataField="Volume" HeaderText="Booked Amt" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"
            SortExpression="Volume">
            <FooterStyle HorizontalAlign="Right" />
            <ItemStyle HorizontalAlign="Right"></ItemStyle>
        </asp:BoundField>
        </asp:BoundField>
         <asp:BoundField DataField="FirstBill" HeaderText="First Bill" HeaderStyle-HorizontalAlign="left" ItemStyle-HorizontalAlign="left"
            SortExpression="FirstBill">
            <FooterStyle HorizontalAlign="Left" />
            <ItemStyle HorizontalAlign="Left"></ItemStyle>
        </asp:BoundField>
    </Columns>
    <FooterStyle BackColor="Aqua" Font-Bold="true" ForeColor="BlueViolet"/>
    

The code behind for sorting is

        switch (e.SortExpression)
        {
            case "Customer":
                if (e.SortDirection == SortDirection.Ascending)
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<string>("CustomerName")
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();
                }
                else
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<string>("CustomerName") descending
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();   
                }                    
                break;

            case "QTY":
                if (e.SortDirection == SortDirection.Ascending)
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<int>("Qty")
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();
                }
                else
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<int>("Qty") descending
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();   
                }                    
                break;

            case "Volume":
                if (e.SortDirection == SortDirection.Ascending)
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<float>("Volume")
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();
                }
                else
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<float>("Volume") descending
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();
                }
                break;

         case "FirstBill":
                if (e.SortDirection == SortDirection.Ascending)
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<DateTime>("FirstBill")
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();
                }
                else
                {
                    var result = from table in Ob.DataTableOther.AsEnumerable()
                                 orderby table.Field<DateTime>("FirstBill") descending
                                 select table;
                    var dv = result.AsDataView();
                    grdReport.DataSource = dv;
                    grdReport.DataBind();
                }
                break;


            default:
                break;
        }

And the row data bound event is

 protected void grdReport_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        # region try
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow && Ob.DatasetMain.Tables[0].Rows.Count != 0)
            {
                if ((Ob.FromDate != null || Ob.FromDate != "") && (Ob.UptoDate != null || Ob.UptoDate != ""))
                {

                    ((HyperLink)e.Row.Cells[2].FindControl("hplNavigate")).NavigateUrl =
                       String.Format("~//Reports/BookingByCustomerReport.aspx?BC={0},{1},{2},{3}", Ob.DatasetMain.Tables[0].Rows[Ob.Counter][0], Ob.FromDate, Ob.UptoDate, radReportFrom.Checked);


                    Ob.Counter++;
                }
                if (hdnFromCustomer.Value == "true")
                {
                    ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).Checked = true;
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (Ob.DatasetOther.Tables[0].Rows.Count != 0)
                {
                    e.Row.Cells[2].Text = "Total";
                    e.Row.Cells[3].Text = Ob.DatasetOther.Tables[0].Rows[Ob.DatasetOther.Tables[0].Rows.Count - 1][2].ToString();
                    e.Row.Cells[4].Text = Ob.DatasetOther.Tables[0].Rows[Ob.DatasetOther.Tables[0].Rows.Count - 1][3].ToString();
                    e.Row.Cells[5].Text = Ob.DatasetOther.Tables[0].Rows[Ob.DatasetOther.Tables[0].Rows.Count - 1][4].ToString();
                    e.Row.Cells[6].Text = Ob.DatasetOther.Tables[0].Rows[Ob.DatasetOther.Tables[0].Rows.Count - 1][5].ToString();
                }
            }
        }
        # endregion
        catch (Exception ex)
        { }
    }

To again list out problem

  1. I cannot sort by des when I click again
  2. If I sort out by say, customer name, and then click on qty or any other I get Specified cast is not valid. Means, I cannot sort out by clicking any other column once I sorted by any particular column.

Can anyone help me figure out problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T12:54:56+00:00Added an answer on June 10, 2026 at 12:54 pm

    you have to allow your gridview to sort on your gridview property

     AllowSorting="true" 
    

    moreover you have to store your sort in cache (viewstate or session).use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction.

    Example:

    DataTable sourceTable = GridAttendence.DataSource as DataTable;
    DataView view = new DataView(sourceTable);
    string[] sortData = Session["sortExpression"].ToString().Trim().Split(' ');
    if (e.SortExpression == sortData[0])
    {
        if (sortData[1] == "ASC")
        {
            view.Sort = e.SortExpression + " " + "DESC";
            this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC";
        }
        else
        {
            view.Sort = e.SortExpression + " " + "ASC";
            this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
        }
    }
    else
    {
        view.Sort = e.SortExpression + " " + "ASC";
        this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have used this custom grid view in my code, and I want to
I have grid something like this: Ext.define('Exp.view.dashboard.Tv', { extend: 'Ext.grid.Panel', initComponent: function() { this.columns
I have a View that is basically setup like this: <Grid> <ViewBox> <Grid> <ItemsControl
I encountered a problem whereby the data grid view column does not show more
I have a SQLite database that is displayed in a data grid view in
I'm having some problems with the _SelectionChanged event on an ASPX grid view using
I have a grid view utilizing sql data source. Now I want to delete
I have been suffering with one problem since 2days.I have a grid view in
I'm using MVP pattern, so I have a View that has almost no logic
I have a data grid view with images loaded into it. The table which

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.