datagrid的排序

来源:互联网 发布:淘宝店铺取名 编辑:程序博客网 时间:2024/04/30 20:47
在asp.net中利用datagrid控件按列进行排序很是方便。可是我们只能单项排序!如果我们需要正反排序那么就需要加入一些代码控制一下,下面我来详细讲解一下这个过程。

  首先我们需要将datagird控件的属性设置为 AllowSorting="True",且需要排序列需要制定排序表达式 eg: SortExpression="PlanType"。这些可以在datagrid属性生成器中设置就可以了。设置好这些,我们进入代码文件,来编写响应排序的事件.

  首先在Page_Load时间中加入如下代码:

   if (!IsPostBack)
   {
    if (this.dg.Attributes["SortExpression"] == null)
        {

            this.dg.Attributes["SortExpression"] = "PlanType";
            this.dg.Attributes["SortExpression"] = "PlanDate";
            this.dg.Attributes["SortExpression"] = "COMPANY_NAME";
            this.dg.Attributes["SortExpression"] = "Amt";
            this.dg.Attributes["SortDirection"] = "DESC";
        }
        BindDataGrid();

   }

   private void BindDataGrid()
  {
   da = new SqlDataAdapter(SqlStr, con);

        DataSet ds = new DataSet();
        da.Fill(ds, "table_P_Plan");
        this.dg.DataSource = ds.Tables["table_P_Plan"].DefaultView;
        string SortExpression = dg.Attributes["SortExpression"];
        string SortDirection = dg.Attributes["SortDirection"];
        ds.Tables["table_P_Plan"].DefaultView.Sort = SortExpression + " " + SortDirection;
        this.dg.DataBind();

}

   进行完上面的设置后我们进入重要的环节,排序事件的编写:

  private void kjkm_dg_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
  {
    string SortExpression = e.SortExpression.ToString();  //获得当前排序表达式
        string SortDirection = "ASC"; //为排序方向变量赋初值
        if (SortExpression == dg.Attributes["SortExpression"])  //如果为当前排序列
        {
            SortDirection = (dg.Attributes["SortDirection"].ToString() == SortDirection ? "DESC" : "ASC");     //获得下一次的排序状态

        }
        dg.Attributes["SortExpression"] = SortExpression;
        dg.Attributes["SortDirection"] = SortDirection;
        BindDataGrid();

  }