控件排序事件中用DataView及DataTable排序

在做ASP.NET页面开发时,经常要用到dataset(或者DataTable),绑定到DataGrid或GridView上要进行重新排序,排序规则按照数组fids元素的顺序进行。本文将介绍如何在排序事件用DataView及DataTable实现排序功能.

一般人的做法是用DataView排序,关键代码如下

DataView dv = dt.DefaultView;

dv.Sort = "dis,发布日期 desc";

然后把dv绑定到DataGird输出。

不过问题又来了,如果我们需要分页功能,在翻页时,我们需要ViewState等控件来保存状态啊.那么我们还是需要用到DataTable或DataSet, DataView本身不能被序列化,DataView中的Table属性是未经排序的,所以它在这里不起作用.

于是有个菜鸟级土解决方法如下(只使用了简单的循环):

private DataTable SortTable(DataTable dt,string[] pids)

         {

              DataTable dt0 = dt.Clone(); //复制原表结构

              for(int i=0;i<pids.Length;i++)

              {

                   if(pids[i] != string.Empty)

                   {

                       DataRow[] drs = dt.Select("pos_id=" + pids[i]);

                       if(drs.Length > 0)

                       {

                            foreach(DataRow dr in drs)

                            {

                                 dt0.ImportRow(dr); //导入行

                            }

                       }

                   }

              }

              return dt0;

     }

说明:就是对排序的数组循环,在datatable中找对应的行,然后复制到新表中。

该方法的效率还是可以的,不过如果交集次数大于20,000,000的时候,就会有效率问题.

其实啊,新近版的.NET类库里的DataRow[]集合对象中已经有个CopyToDataTable方法可以解决DataTable排序问题,在控件的排序事件中实现如下代码:

string currentSortColumn = this.SortColumn;//封闭ViewState变量的属性
      this.SortColumn = e.SortExpression;

 if (currentSortColumn == this.SortColumn)
                this.SortAscending = !this.SortAscending;//封闭ViewState变量的属性

       else
                this.SortAscending = false;

DataTable dt = (DataTable)ViewState["DataSource"];
      DataRow[] filter = dt.Select("",this.SortColumn + " " + (this.SortAscending? "ASC" : "DESC"));
      DataTable newTable = filter.CopyToDataTable();
      ViewState["DataSource"] = newTable;
      this.BindDateGrid();

但我们却不知道CopyToDataTable的效率是否足够好.




评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.