DataGrid自定义排序要在3个部分写代码如下:
1.
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
//设置排序表达式
ViewState["SortOrder"] = "AA";//设置要排序设置的字段
//设置排序的升降序
ViewState["OrderDire"] = "ASC";
//MessageBox.ShowConfirm(ImageButton3,"确定删除?");
GridBind();
}
}
2.
protected void GridBind()
{
....//连接数据库
DataSet ds = new DataSet();
da.Fill(ds,"table1");
// DataGrid1.DataSource = ds.Tables[0];
// DataGrid1.DataKeyField = ds.Tables[0].Columns["DD"].ToString();
DataView view = ds.Tables["table1"].DefaultView;
//设置排序关键字
string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
//设置排序表达式
view.Sort = sort;
//数据邦定
DataGrid1.DataSource = view;
DataGrid1.DataBind();
}
3.
private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
//取得排序表达式
string vortExp = e.SortExpression;
//如果是当前排序表达式
if(ViewState["SortOrder"].ToString() == vortExp)
{
//如果原来是降序则改为升序,反之亦然
if((string)ViewState["OrderDire"] == "Desc")
ViewState["OrderDire"] = "ASC";
else
ViewState["OrderDire"] = "Desc";
}
else
{
//重新设置排序关键字
ViewState["SortOrder"] = e.SortExpression;
}
GridBind();
}