【问题标题】:Cannot sort gridview in des order, neither can sort on another column?无法按des顺序对gridview进行排序,也不能对另一列进行排序?
【发布时间】:2012-08-25 09:49:37
【问题描述】:

我有这个网格视图,它有 2 个问题。

  1. 如果我通过单击某列对其进行排序,然后再次单击,则其未按 des 顺序排序。
  2. 如果我使用col A 排序,然后单击任何其他列,它不会再次排序?

      <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"/>
    

排序的代码是

        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;
        }

而行数据绑定事件是

 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)
        { }
    }

再次列出问题

  1. 再次单击时无法按 des 排序
  2. 如果我按客户名称进行排序,然后单击qty 或任何其他我得到Specified cast is not valid. 的意思是,一旦按任何特定列排序,我就无法通过单击任何其他列进行排序。

谁能帮我解决问题?

【问题讨论】:

    标签: c# asp.net sorting gridview


    【解决方案1】:

    您必须允许您的 gridview 对您的 gridview 属性进行排序

     AllowSorting="true" 
    

    此外,您必须将排序存储在缓存中(视图状态或会话)。使用会话变量来存储最新的排序表达式,并且当您下次对网格进行排序时,将网格的排序表达式与最后存储的 Session 变量进行比较排序表达式。如果列相等,则检查先前排序的方向并按相反方向排序。

    例子:

    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";
    }
    

    【讨论】:

    • 你可能想把Session["sortExpression"]改成ViewState["sortExpression"]
    【解决方案2】:

    在网格中,当 AutoGenerateColumns = “false”时,e.SortDirection 将始终为升序。解决方法是您需要在 ViewState 中存储列的最后一个排序顺序(或者存储每列的最后一个排序顺序)

        public const string ASCENDING = "Ascending";
        public const string DESCENDING = "Descending";
    

    定义属性,保留SortOrder

        public string GridSortOrder
        {
            get { return Convert.ToString(ViewState["SortOrderKey"]) == string.Empty ? ASCENDING : "Descending"; }
            set { ViewState["SortOrderKey"] = value; }
        }
    

    在 grdReport_Sorting 事件中,使

         if (GridSortOrder == 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();   
            }
    
             /*
             * logic for remaining columns 
             */
    
            //Change the sortOrder
            ChangeSortOrder(GridSortOrder);
    

    更改排序方式

        public void ChangeSortOrder(string currentOrder)
        {
            GridSortOrder = currentOrder == ASCENDING ? DESCENDING : ASCENDING;
        }
    

    【讨论】:

      【解决方案3】:

      试试这个方法

      private const string ASCENDING = " ASC";
      private const string DESCENDING = " DESC";
      static private DataView dvReports;
      
      protected void Page_Load(object sender, EventArgs e)
      {
          if (!IsPostBack)
          {
              // i am assuming that you are binding the gridview on page_load
              // you can use the same on a button click event too
              dvReports = new DataView(Ob.DataTableOther);
              BindGridView();
          }
      }
      
      protected void grdReport_Sorting(object sender, GridViewSortEventArgs e)
      {
          string sortExpression = e.SortExpression;
      
          if (GridViewSortDirection == SortDirection.Ascending)
          {
              GridViewSortDirection = SortDirection.Descending;
              dvProducts.Sort = sortExpression + DESCENDING;
          }
          else
          {
              GridViewSortDirection = SortDirection.Ascending;
              dvProducts.Sort = sortExpression + ASCENDING;
          }
          BindGridView();
      }
      
      private void BindGridView()
      {
          GridView1.DataSource = dvReports
          GridView1.DataBind();
      }
      
      public SortDirection GridViewSortDirection
      {
          get
          {
              if (ViewState["sortDirection"] == null)
                  ViewState["sortDirection"] = SortDirection.Ascending;
      
              return (SortDirection)ViewState["sortDirection"];
          }
          set { ViewState["sortDirection"] = value; }
      }
      

      我正在为您写这篇文章,因为如果您与 DataTable 绑定,则无需将其设为 IEnumerable 并进行自定义排序。这不是必需的,还有更多的代码行。

      框架是你的朋友。快乐编码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-29
        • 2012-12-08
        • 2020-09-29
        • 1970-01-01
        相关资源
        最近更新 更多