Telerik UI For WinForms--关于RadGridView的列排序
在使用RadGridView绑定数据后,我希望属性的显示顺序按继承层次显示,但实际是相反的。下面示例两个类:
public class A { public string Astr { get; set; } public int Aint { get; set; } } public class B : A { public string Bstr { get; set; } public int Bint { get; set; } }
实例化一个B类的集合,然后绑定到RadGridView控件:
List<B> list = new List<B>(); list.Add(new B() { Astr = "astr", Aint = 7, Bstr = "bstr", Bint = 8 }); radGridView1.DataSource = list;
显示效果:
很明显,先显示子类的属性,再显示基类的属性。而通过反射获取类型B的属性也是这个顺序。查了资料,没有找到很舒服的解决方法,如果你有,恳请赐教。下面是我的解决思路:
考虑从基类型Object开始到B类型,获取继承层次中每个类型的属性,用到反射和递归,代码如下:
public static List<string> GetPropertyNames(Type type) { var list = new List<string>(); if (type != null && type.IsClass) { Type basetype = type.BaseType; if (basetype != null) { list = GetPropertyNames(basetype); } PropertyInfo[] propertyInfos = type.GetProperties(); List<string> curTypeList = propertyInfos.Select(propertyInfo => propertyInfo.Name).ToList(); list.AddRange(curTypeList.Except(list)); } return list; }
获取了属性的顺序列表,接下来就要对RadGridView控件的列进行排序,代码如下:
List<B> list = new List<B>(); list.Add(new B() { Astr = "astr", Aint = 7, Bstr = "bstr", Bint = 8 }); radGridView1.DataSource = list; Type typeB = typeof(B); List<string> attList = GetPropertyNames(typeB); var sortedIndex = SortColumn(radGridView1.Columns, attList); foreach (var i in sortedIndex) { int index = GetColumnIndex(radGridView1.Columns, i.Key); if (index != i.Value) radGridView1.Columns.Move(index, i.Value); }
用到的辅助方法:
public static SortedList<string, int> SortColumn(GridViewColumnCollection columnCollection, List<string> list) { var sortedList = new SortedList<string, int>(); int i = 0; foreach (var item in list) { int columnIndex = GetColumnIndex(columnCollection, item); if (columnIndex != -1) { sortedList.Add(item, i); i++; } } return sortedList; } public static int GetColumnIndex(GridViewColumnCollection columnCollection, string name) { int count = columnCollection.Count; for (int i = 0; i < count; i++) { if (columnCollection[i].Name == name) return i; } return -1; }
在DataGridView中,可以通过DataGridViewColumn的DisplayIndex属性设置列的显示顺序,而Index是不变的。在RadGridView中,则要通过Move方法将列从原位置移到新位置。
我总觉得有更好的解决方法,如果你有,望赐教。