我有一个位于更新面板中的网格视图。当您单击列标题时,排序工作正常,但如果我转到下一页,排序就会丢失。我将提供下面的代码,如果有人知道如何摆脱这种混乱,请帮忙!
在 Page_Load 中调用 ShowGrid() 函数。我猜问题在于在分页函数中调用 ShowGrid()。
//Show Grid based on argument type
protected void ShowGrid(string arg)
{
//dataset to hold email addresses
DataSet ds = new DataSet();
try
{
//open connection with new connection string
conn.Open();
String selectString = String.Format("SELECT * FROM hr_OnlineJobApp"
+ " WHERE adminCategory='" + adminCategory + "'"
+ "AND departmentApplyingFor LIKE '" + dept + "' ORDER BY {0} {1}", ViewState["sortExp"], ViewState["sortOrder"]);
SqlCommand cmd = new SqlCommand(selectString, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
//bind to gridview
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.PageIndex = Convert.ToInt32(ViewState["pageIndex"]);
}
finally
{
if (conn != null)
conn.Close();
}
}
/**********************************************
* Paging functionality
* *******************************************/
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
//reshow Grid with current type
adminCategory = GridView1.DataKeys[0]["adminCategory"].ToString();
ViewState["pageIndex"] = e.NewPageIndex.ToString();
ShowGrid(adminCategory);
}
/**********************************************
* Sorting functionality
* *******************************************/
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExp = e.SortExpression;
ViewState["sortExp"] = sortExp;
string sortDir = (string)ViewState["sortOrder"];
//Changes the sortDir
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
try
{
conn.Open();
string sql = "SELECT * FROM hr_OnlineJobApp"
+ " WHERE adminCategory='" + adminCategory + "'"
+ "AND departmentApplyingFor LIKE '" + dept + "' ORDER BY " + sortExp + " " + sortDir;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(sql, conn);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);
GridView1.DataSource = myDataSet;
GridView1.DataBind();
}
finally
{
conn.Close();
}
}