zoukankan      html  css  js  c++  java
  • [DataTable]控件排序事件中用DataView及DataTable排序

    控件排序事件中用DataView及DataTable排序
    文章分类:.net编程 
    在做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排序问题
    ,在控件的排序事件中实现如下代码:
    
    C#代码  
    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();  
    
    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的效率是否足够好.
  • 相关阅读:
    mysql 设置自增主键id的起始值
    一文搞定MySQL的事务和隔离级别
    SpringBoot2.0整合Redis
    Redis Cluster搭建高可用Redis服务器集群
    为什么单线程的Redis这么快?
    Spring Boot使用AOP在控制台打印请求、响应信息
    Spring boot集成spring session实现session共享
    SpringBoot项目在IntelliJ IDEA中实现热部署
    Spring Boot入门-快速搭建web项目
    一篇文章搞定SpringMVC参数绑定
  • 原文地址:https://www.cnblogs.com/beeone/p/3618126.html
Copyright © 2011-2022 走看看