unit ListSort;
interface
uses SysUtils, ComCtrls;
type
TSortStyle = (ssAlpha, ssNumeric, ssDateTime);
TSortInfo = record
FcolIndex : Integer; //需要排序的列
FStyle : TSortStyle; //排序的数据类型
FAscending : Boolean; //是否是升序
end;
PSortInfo = ^TSortInfo;
{***************************** 入口函数 *****************************}
procedure SortListView(nListView: TCustomListView; nColIndex: Integer;
nStyle: TSortStyle; Ascending: Boolean = True);
{***************************** 入口函数 *****************************}
implementation
function Sign(Val: Extended): Integer;
begin
if Val<0 then
Result := -1
else
if Val>0 then
Result := 1
else
Result := 0;
end;
//Name: ExtractNum
//Param: 预分析的字符串
//Return: 返回nStr中的数字字符
function ExtractNum(const nStr: string): string;
var i: integer;
begin
result := '';
for i := Length(nStr) downto 1 do
if nStr in ['0'..'9'] then result := nStr + result;
end;
function ListViewCompare(I1, I2: TListItem; Data: Integer): Integer; stdcall;
var V1, V2: string;
begin
with PSortInfo(Data)^ do
begin
if FcolIndex = 0 then
begin
V1 := I1.Caption;
V2 := I2.Caption;
end
else
begin
V1 := I1.SubItems[FcolIndex - 1];
V2 := I2.SubItems[FcolIndex - 1];
end;
case FStyle of
ssAlpha:
Result := AnsiCompareText(V1, V2);
ssNumeric:
Result := Sign(StrToFloat(ExtractNum(V1)) - StrToFloat(ExtractNum(V2)));
ssDateTime:
Result := Sign(StrToDateTime(V1) - StrToDateTime(V2));
else
Result := 0;
end;
if not FAscending then Result := -Result;
end;
end;
//Name; SortListView
//Param:nStyle,排序数据类型; Ascending,默认为升序
//Description: 对nListView指定的ColIndex进行升/降排序
procedure SortListView(nListView: TCustomListView; nColIndex: Integer;
nStyle: TSortStyle; Ascending: Boolean = True);
var nSortInfo: TSortInfo;
begin
nSortInfo.FcolIndex := nColIndex;
nSortInfo.FStyle := nStyle;
nSortInfo.FAscending := Ascending;
nListView.CustomSort(@ListViewCompare, LongInt(@nSortInfo));
end;