一般可在Page_Load事件里定义排序字段和排序升降顺序,例如:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//排序字段,降序、升序
ViewState["SortExp"] = "MONTH";
ViewState["SortDir"] = "ASC";
}
}
然后定义GridView_Sorting事件,其实是对DataTable排序,因为GridView的数据源是DataTable
//排序事件
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet ds = new DataSet();
//下面省略一千行
if (ViewState["SortDir"].ToString().Equals("ASC"))
{
ViewState["SortDir"] = "DESC";
dt.DefaultView.Sort = e.SortExpression + " DESC";
this.gv.Columns[0].HeaderText = this.gv.Columns[0].HeaderText
+ "▼";
}
else
{
ViewState["SortDir"] = "ASC";
dt.DefaultView.Sort = e.SortExpression + " ASC";
this.gv.Columns[0].HeaderText = this.gv.Columns[0].HeaderText + "▲";
}
this.gv.DataSource = dt.DefaultView;
this.gv.DataBind();
}