问题:
我想允许在我的 GridView 上进行排序(ASC/DESC)和过滤。
我已经设法通过我DropDownList
的. 但是,当用户从 DropDownList 中选择一个过滤器,然后尝试对结果数据进行排序时,GridView 会“忘记”当前选择的过滤器并仅对我的所有数据进行排序,而不是像您期望的那样对过滤后的数据进行排序。DataBound
GridView
我试过的:
这是我的过滤代码...
private void FilterGridView()
{
SqlCommand command = new SqlCommand();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = WebConfigurationManager.ConnectionStrings[1].ConnectionString;
command.CommandText = string.Format("SELECT * FROM Products WHERE {0} = 1", ddlProdFilter.SelectedValue);
if (ddlProdFilter.SelectedValue == "on_sale")
{
command.CommandText = "SELECT * FROM Products INNER JOIN ProductVariants ON [Products].product_id = [ProductVariants].product_id WHERE [ProductVariants].on_sale = 1";
}
else if (ddlProdFilter.SelectedValue == "*")
{
command.CommandText = "SELECT * FROM Products";
}
command.Connection = connection;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
sqlAdapter.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
{
pnlNoProducts.Visible = true;
}
else
{
pnlNoProducts.Visible = false;
}
gvAllProducts.DataSource = ds;
}
下拉列表中选择的值对应于我表中的列名。
这是我的排序代码...
private void SortGridView(string sortExpression, string sortDir)
{
SqlCommand command = new SqlCommand();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = WebConfigurationManager.ConnectionStrings[1].ConnectionString;
if (!string.IsNullOrEmpty(sortDir))
{
command.CommandText = "SELECT * FROM Products ORDER BY " + sortExpression + " " + sortDir;
}
command.Connection = connection;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
sqlAdapter.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
gvAllProducts.DataSource = dt;
}
其中sortExpression
对应于选定DataBound
字段,例如product_id
,最后,sortDir
是一个会话变量,用于准确跟踪回发之间的排序顺序。
事件处理程序。
protected void gvAllProducts_OnSorting(object sender, GridViewSortEventArgs e)
{
if (e.SortDirection == SortDirection.Ascending && SessionHelper.GetSessionStringValue("SORT_DIRECTION") != "DESC")//if ascending and the last sort order wasn't descending, sort by DSC
{
SessionHelper.SetSessionValue("DESC", "SORT_DIRECTION");
}
else if (SessionHelper.GetSessionStringValue("SORT_DIRECTION") == "DESC")//otherwise, if the last sort order was desc, sort asc
{
SessionHelper.SetSessionValue("ASC", "SORT_DIRECTION");
}
SortGridView(e.SortExpression, SessionHelper.GetSessionStringValue("SORT_DIRECTION"));
BindDataSource();
e.Cancel = true;
}
protected void ddlProdFilter_SelectedIndexChanged(object sender, EventArgs e)
{
FilterGridView();
BindDataSource();
}
protected void gvAllProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvAllProducts.PageIndex = e.NewPageIndex;
FilterGridView();
BindDataSource();
}
我尝试在进行排序时/之后调用过滤代码,这很有意义,但同样的事情也会发生。我已经用谷歌搜索了大约 2 个小时,但找不到解决方案。
以前有没有人遇到过这个问题?你能在这里提供一个潜在的解决方案或一些指导吗?
谢谢