Delphi7的ListView点击列头实现排序

2025-10-26 04:42:40

1、打开Delphi7集成开发环境,在默认工程的Form1窗体放一个ListView1控件,并右键ListView1控件,打开Column editor对话框,新建三个列,Capiton分别为姓名,班级,成绩。

Delphi7的ListView点击列头实现排序

Delphi7的ListView点击列头实现排序

2、将ListView1的ViewStyle设为vsReport,GoldLines显示设为True。

Delphi7的ListView点击列头实现排序

Delphi7的ListView点击列头实现排序

3、在Form1窗体的OnShow事件响应方法中,为ListView1添加数据,代码如下:

procedure TForm1.FormShow(Sender: TObject);

var

  item:TListItem;

begin

  item := ListView1.items.add();

  item.Caption := '小王';

  item.SubItems.Add('一班选板膨');

  item.SubItems.Add('80');

  item := ListView1.items.add();

  item.Caption := '小赵';

  item.SubItems.Add('一班');

  item.SubItems.Add('60');

  item := ListView1.items.add();

  item.Caption := '小李';

  item.SubItems.Add('一班');

  item.SubItems.Add('70');

  item := ListView1.items.add();

  item.Caption := '小韩';

  item.SubItems.Add('一班');

  item.SubItems.Add('80');

end;

Delphi7的ListView点击列头实现排序

4、F9运行程序,可以看到数据被正常添加并显示了

Delphi7的ListView点击列头实现排序

5、接着在番胳Unit.pas的var Form1:TForm1下加一个全局变量 : 

m_bSort:   boolean=false;

在程序implement部分定义如下函数:

function CustomSortProc(Item1, Item2: TListItem; Index: integer): integer;stdcall;

var

c1,c2 :string;

begin

  if index<>0 then

  begin

    c1:= Item1.SubItems.Strings[index-1];

    c2:= Item2.SubItems.Strings[index-1];

    if m_bSort then

    begin

      Result := CompareText(c1,c2);

    end

    else

    begin

      Result := -CompareText(c1,c2);

    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;

这个是ListView1进行比较两行数据大小番露的回调函数,我们可以自己定义,然后在ListView1的OnColumnClick事件中进行调用。

6、在ListView1的OnColumnClick事件中写如下代码:

procedure TForm1.ListView1ColumnClick(Sender: TObject;

  Column: TListColumn);

begin

      ListView1.CustomSort(@CustomSortProc,Column.Index);

      m_bSort := not m_bSort;

end;

Delphi7的ListView点击列头实现排序

7、F9运行程序,点击列头就能看到ListView1的排序了

Delphi7的ListView点击列头实现排序

Delphi7的ListView点击列头实现排序

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢