【发布时间】: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