在不返回 SQL 的情况下对 GridView 进行排序

Sort a GridView without going back to SQL

我有一个 gridview,我用它来显示来自 storedProcedure 的数据。我现在想对数据进行排序,但很多地方都说我必须返回 sql 才能执行此操作。 Maby 我不理解给出的解释,但我认为那是不对的。我已经简化了问题,并希望获得有关如何对绑定列进行排序的任何帮助。这是我的 aspx 页面。

    <asp:GridView  ID="BannerGrid" runat="server" AllowSorting="True" onSorting="Sorts" GridLines="None" AutoGenerateColumns="false" OnRowCreated="BannerGrid_RowCreated">
        <Columns>
            <asp:Boundfield DataField="BannerID" HeaderText="Banner ID" SortExpression="BannerID"/> </Columns>

后面是我的 C# 代码:

            SqlConnection sqlConnection1 = new SqlConnection(conn);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "GetDifferenceInteraction";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ADate", TodayDate);
        cmd.Parameters.AddWithValue("@BDate", YesDate);
        SqlDataReader reader;
        cmd.Connection = sqlConnection1;

        sqlConnection1.Open();

        reader = cmd.ExecuteReader();
        BannerGrid.DataSource = reader;
        BannerGrid.DataBind();
        reader.Close();
        sqlConnection1.Close();

有关如何在 c# itelf 中对此进行排序的任何帮助。提前致谢!

如果我没记错的话,您可以将数据加载到其中包含 DataTable 的 DataSet。然后把它绑定到你的 GridView.This provides much 更多的功能,将允许您的排序。但是最好先安排一个产生结果集的查询。

您可以将数据存储在 ViewState 变量中,但如果数据非常大,可能会导致问题。

...
reader = cmd.ExecuteReader();
//here you should save your data, I stored mine in a DataTable type like this
dtStored.Load(reader);
BannerGrid.DataSource = reader;
BannerGrid.DataBind();
reader.Close();
...

我有这四个属性

    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";
    private SortDirection gvSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
    private DataTable dtStored
    {
        get { return (ViewState["dt"] == null) ? null : (DataTable)ViewState["dt"]; }
        set { ViewState["dt"] = value; }
    }

在你的排序活动中你可以有这个

    protected void BannerGrid_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;
        string direction = ASCENDING;

        if (gvSortDirection == SortDirection.Ascending)
        {
            gvSortDirection = SortDirection.Descending;
            direction = DESCENDING;
        }
        else
        {
            gvSortDirection = SortDirection.Ascending;
            direction = ASCENDING;
        }
        try
        {   
            DataTable dt = dtStored;

            DataView dv = new DataView(dt);
            dv.Sort = sortExpression + direction;

            BannerGrid.DataSource = dv;
            BannerGrid.DataBind();     
        }
        catch (Exception ex)
        {
            //Log error
        }
    }