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