【问题标题】:Manually Sorting Data in Gridview in asp.Net Webforms在 asp.Net Webforms 的 Gridview 中手动对数据进行排序
【发布时间】:2016-05-04 14:06:12
【问题描述】:

我在 gridview 上手动排序数据时遇到了一些困难。我使用了一个数据集,当将 AllowSort 设置为 true 时,还编写了代码来根据https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx 上给出的指南处理排序。但是,当我运行我的代码时,数据会显示,但是当我单击每列的标题时,什么也没有发生。 这是我的代码

 protected void Page_Load(object sender, EventArgs e)
    {


       string connstring = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
        SqlConnection conn = new SqlConnection(connstring);
        conn.Open();
        SqlCommand comm = conn.CreateCommand();


    comm.CommandText = "SELECT Count(Student.StudentID) AS StdCount, Schools.Name, Schools.StartDate, School.SchoolFees FROM Schools INNER JOIN Students ON Schools.SchoolID = Student.SchoolID WHERE School.Active = 1 GROUP BY Schools.Name, Schools.StartDate, Schools.SchoolFess ORDER BY Schools.Name ASC";
        SqlDataAdapter da = new SqlDataAdapter(comm);

        DataSet ds = new DataSet();

         da.Fill(ds);

        if (ds.Tables.Count > 0)
        {
            DataTable dt = ds.Tables[0];

            ViewState["datable"] = dt;
        }



        GridView1.DataSource = ds;
        GridView1.DataBind(); 

    }
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

        //Retrieve the table from the session object.
        DataTable dt = (DataTable)ViewState["datable"];

        if (dt != null)
        {

            //Sort the data.
            dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
            GridView1.DataSource = ViewState["datable"];
            GridView1.DataBind();
        }

    }

    private string GetSortDirection(string column)
    {

        // By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        // Retrieve the last column that was sorted.
        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            // Check if the same column is being sorted.
            // Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        // Save new values in ViewState.
        ViewState["SortDirection"] = sortDirection;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 您是否调试过返回您的函数的值?创建一个变量string sortOrder = GetSortDirection(e.SortExpression); 并在那里放置一个断点
  • 请不要在 ViewState 中存储数据表等对象。 ViewState 并非旨在用作重物的缓存机制。对数据库或服务器端缓存执行另一个查询,但不是视图状态。
  • 此外,您正在将 GridView 与每个 page_load 上的数据重新绑定。没必要,把这段代码包裹在if (!Page.IsPostback)
  • 感谢大家的快速回复。我添加了一个断点,就像你说的@Juan,我注意到执行不会在那个时候中断。就好像事件甚至没有触发一样。
  • 谢谢@Andrei,会做出更正。

标签: sql asp.net sql-server gridview webforms


【解决方案1】:

你需要绑定DataTable的DefaultView,就是这个有序的,不是ViewState变量。

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    //Retrieve the table from the session object.
    DataTable dt = (DataTable)ViewState["datable"];
    if (dt != null)
    {
        //Sort the data.
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }
}

【讨论】:

  • 谢谢@Rocoso。我已经按照你上面说的修改了代码,但它仍然不起作用。当我单击时,没有任何反应,就像事件没有被触发一样。我在 GridView1_Sorting 代码块中添加了一个断点,并且断点永远不会到达。
  • 我刚刚发现 EnableSortingAndPagingCallbacks 设置为“true”,这就是事件未触发的原因。我将其设置为 false 并且事件触发。但是这种排序只发生一次。当我再次单击时,页面只是重新加载并且没有排序。感谢您的帮助。
  • 找出问题所在。排序现在工作得很好。非常感谢
【解决方案2】:

这看起来是Page LifeCycle 问题。

每次你回发整个页面生命周期运行

在您的情况下,您会在每次回发时检索并覆盖 ViewState["datable"],当然假设 if (ds.Tables.Count > 0) 的计算结果为 true。

然后您在页面加载中执行此操作:

GridView1.DataSource = ds;

但在您的排序例程中您可以访问:

DataTable dt = (DataTable)ViewState["datable"];
...
GridView1.DataSource = ViewState["datable"];

您刚刚将 GridView.DataSource(最初是一个 DataSet)替换为一个 DataTable

像这样在 PageLoad 中包装你的初始数据检索

if( !Page.IsPostback )
{
   // This retrieves Data once, and you persist it 
   // in the ViewState no need to Keep retrieving it 
   // unless the data has changed
}

// Rebind outside the if
GridView1.DataSource = (DataTable) ViewState["datable"];
GridView1.DataBind();

附录

每安德烈他是正确的。 ViewState 是渲染的 ASPX 上的隐藏字段。在浏览器中查看页面源并搜索

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />

只要数据集较小且不包含任何机密信息,就可以用作学习辅助工具。

但是,由于它在每次回发时都会传入和传出您的页面,因此您会产生大量开销。想象一下,如果您的 DataSet 包含数千行。

会话状态是更好的选择,但应用程序缓存更好。像SqlDataSource 这样的服务器数据控件使用这个缓存,你也可以。像 ViewState 一样访问它:

ViewState["datable"] = dt;

Cache["datable"] = dt;

但不要为此而疯狂。 ViewState、SessionState、Cookies、LocalStorage等都有自己的位置,学习一下吧。

【讨论】:

  • 谢谢@fnostro。我听从了 Andrei 的建议,并使用了一个会话来保存数据表。排序例程现在有效,但它只是按降序排序,当我再次单击时,页面重新加载并且不按升序排序。
  • 我调试后发现我犯了一个错误,调用了我的排序函数两次,这就是排序不能正常工作的原因。感谢@fnostro 的帮助。
猜你喜欢
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
  • 2016-05-26
  • 1970-01-01
  • 2012-11-02
相关资源
最近更新 更多