日新阁

取日三省之意,记生活珠玑,每日清新,谓日新阁.

 

一个据说含DataGrid Sort功能的代码。

http://www.codeproject.com/csharp/datagridsort.asp

public class MyDataGrid : DataGrid
{
 
//sort a column by its index
 public void SortColumn(int columnIndex)
 
{
  
if(this.DataSource!=null && 
    ((System.Collections.IList)
this.DataSource).Count>0)
  
{
   
//discover the TYPE of underlying objects
   Type sourceType = ((System.Collections.IList)this.DataSource)[0].GetType();

   
//get the PropertyDescriptor for a sorted column
   
//assume TableStyles[0] is used for our datagrid (change it if necessary)
   System.ComponentModel.PropertyDescriptor pd =
    
this.TableStyles[0].GridColumnStyles[columnIndex].PropertyDescriptor;

   
//if the above line of code didn't work try to get a propertydescriptor
   
// via MappingName
   if(pd == null)
   
{
    System.ComponentModel.PropertyDescriptorCollection pdc 
=
     System.ComponentModel.TypeDescriptor.GetProperties(sourceType);
    pd 
=
     pdc.Find( 
this.TableStyles[0].GridColumnStyles[columnIndex].MappingName, 
                                                                      
false);
   }


   
//now invoke ColumnHeaderClicked method using system.reflection tools
   System.Reflection.MethodInfo mi =
    
typeof(System.Windows.Forms.DataGrid).GetMethod("ColumnHeaderClicked",
     System.Reflection.BindingFlags.Instance 
|
     System.Reflection.BindingFlags.NonPublic);
   mi.Invoke(
thisnew object[] { pd });
  }

 }

}

以上代码,我一开始用的时候还可以排序,但是后来发现,鼠标点一下后,必须移动到别的地方,才能看到排序效果。不知道是不是新加了MouseDown引起的。
于是到处查找不同方法的排序代码。戏剧性的是,测试的时候,我把所有的排序功能代码都屏蔽了。这时竟然DataGrid完全可以排序。狂哭啊,狂哭。早知道这样,我何必到处查找排序方法啊。  哎……

posted on 2007-06-05 09:18  flashicp  阅读(273)  评论(0编辑  收藏  举报

导航