1. 程式人生 > >Delphi listview 點選列頭排序

Delphi listview 點選列頭排序

listview 的數字排序。

首先新增全域性變數

 m_bSort: Boolean = false;//控制雙向排序
function CustomSortProc(Item1, Item2: TListItem; ParamSort: Integer): Integer;stdcall;

之後在需要排序的listview 控制元件的OnColumClick 事件中編寫程式碼

 procedure TMainForm.lv_UpLoadListColumnClick(Sender: TObject;
    Column: TListColumn);
  begin
    if (Column.Index
= 1) or (Column.Index = 3) then begin lv_UpLoadList.CustomSort(@CustomSortProc, Column.Index); m_bSort := not m_bSort; end; end;

之後編寫全域性函式

function CustomSortProc(Item1, Item2: TListItem;
    ParamSort: Integer): Integer; stdcall;
  var
    // txt1, txt2: string;
    txt1, txt2: Integer;
  begin
if ParamSort <> 0 then begin try txt1 := StrToInt(Item1.SubItems.Strings[ParamSort - 1]); txt2 := StrToInt(Item2.SubItems.Strings[ParamSort - 1]); if m_bSort then begin // Result := CompareText(txt1, txt2); Result := txt1 - txt2; end
else begin Result := -(txt1 - txt2); // Result := -CompareText(txt1, txt2); end; except end; end else begin if m_bSort then begin Result := CompareText(Item1.Caption, Item2.Caption); end else begin Result := -CompareText(Item1.Caption, Item2.Caption); end; end; end;

以上是數字的排序,如果需要漢字什麼的排序,這將上面的strtoint去掉,並將上面的註釋行替換上面的行就行了