0

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

  1. 如果我通过单击一列对其进行排序,然后再次单击,则它不是按 des 顺序排序的。
  2. 如果我用 a 排序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.的意思,一旦我按任何特定列排序,我就无法通过单击任何其他列进行排序。

谁能帮我解决问题?

4

3 回答 3

1

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

 AllowSorting="true" 

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

例子:

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";
}
于 2012-08-25T10:13:01.820 回答
1

在网格中,当 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;
    }
于 2012-08-25T10:40:04.283 回答
0

试试这个方法

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

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

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

于 2012-08-25T10:50:37.213 回答