我有一个更新面板中的gridview。单击列标题时排序工作正常但如果我转到下一页,排序将丢失。我将在下面提供代码,如果有人知道如何摆脱这种混乱,请帮忙!
在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();
}
}
答案 0 :(得分:2)
您正在PageIndex
中将Showgrid
设置为0:
GridView1.PageIndex = 0;
因此,您将覆盖PageIndexChanging
GridView1.PageIndex = e.NewPageIndex;
因此,您无需在ShowGrid中设置PageIndex来解决问题。
该问题的另一个可能原因:
也许你是在Page_Load
的每个回发中对GridView进行数据绑定。你应该只在第一次这样做。使用Page.IsPostBack
属性:
protected void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
ShowGrid();
}
最后但并非最不重要:仅在用户点击gridView_Sorting
中的标题时才进行排序。您还应该在ORDER BY
中应用ShowGrid
或仅使用一种方法来对GridView进行数据绑定。但是你总是在那里date desc
订购。
您不应该使用DataView来应用排序,而应该首先在sql中使用ORDER BY
。
String sql = String.Format("SELECT * FROM hr_OnlineJobApp"
+ " WHERE adminCategory='"+adminCategory+"'"
+ " ORDER BY {0} {1}", sortExp, sortDir);
SqlCommand mySqlCommand = new SqlCommand(sql, conn);
答案 1 :(得分:0)
在ShowGrid()函数中设置GridView1.PageIndex = 0,然后在Page_Load event.So上调用该函数,在每次回发时,页面索引都设置为0,这会产生问题。您应该删除该行以解决问题。