New class
Public classSortablebindinglist<t>: bindinglist<t> { Private BOOLIssortedcore =true; PrivateListSortDirection SortDirectionCore =listsortdirection.ascending; PrivatePropertyDescriptor SortPropertyCore =NULL; Private stringDefaultsortitem; PublicSortableBindingList ():Base() { } PublicSortableBindingList (ilist<t> list):Base(list) {}protected Override BOOLSupportsSortingCore {Get{return true; } } protected Override BOOLSupportsSearchingCore {Get{return true; } } protected Override BOOLIssortedcore {Get{returnIssortedcore;} } protected Overridelistsortdirection SortDirectionCore {Get{returnSortDirectionCore;} } protected OverridePropertyDescriptor SortPropertyCore {Get{returnSortPropertyCore;} } protected Override intFindCore (PropertyDescriptor prop,Objectkey) { for(inti =0; I < This. Count; i++) { if(Equals (Prop. GetValue ( This[i]), key)returni; } return-1; } protected Override voidApplySortCore (PropertyDescriptor prop, listsortdirection direction) {Issortedcore=true; SortPropertyCore=prop; SortDirectionCore=direction; Sort (); } protected Override voidRemoveSortCore () {if(issortedcore) {Issortedcore=false; SortPropertyCore=NULL; SortDirectionCore=listsortdirection.ascending; Sort (); } } Public stringDefaultsortitem {Get{returnDefaultsortitem;} Set { if(Defaultsortitem! =value) {Defaultsortitem=value; Sort (); } } } Private voidSort () {List<T> list = ( This. Items asList<t>); List. Sort (Comparecore); Resetbindings (); } Private intComparecore (t O1, T O2) {intRET =0; if(SortPropertyCore! =NULL) {ret=CompareValue (Sortpropertycore.getvalue (O1), Sortpropertycore.getvalue (O2), sortpropertycore.propertytype); } if(ret = =0&& Defaultsortitem! =NULL) {PropertyInfo property=typeof(T). GetProperty (Defaultsortitem, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance | Bindingflags.ignorecase,NULL,NULL,Newtype[0],NULL); if(Property! =NULL) {ret= CompareValue (property. GetValue (O1,NULL), property. GetValue (O2,NULL), property. PropertyType); } } if(SortDirectionCore = = listsortdirection.descending) ret =-ret; returnret; } Private Static intCompareValue (ObjectO1,ObjectO2, type type) { //MessageBox.Show (type. GetType (). ToString ()); if(O1 = =NULL)returnO2 = =NULL?0: -1; if(O2 = =NULL)return 1; if(Type. ToString (). Contains ("Int"))returnconvert.todouble (O1). CompareTo (Convert.todouble (O2));//Note if
(type.IsPrimitive || type.IsEnum)是取不到Int型的
here if(Type = =typeof(DateTime))returnconvert.todatetime (O1). CompareTo (O2); returnString.Compare (O1. ToString (). Trim (), O2. ToString (). Trim ()); } Use: (Just throw the query list<> in.)
New App_code.sortablebindinglist<app_code.wordcount> (new APP_CODE.WORLDCOUNTDA (). SelectAll ());
Haven't tried the date yet.
C # implementation DataGridView Automatic sorting