首页 | 社区 | 博客 | 招聘 | 文章 | 新闻 | 下载 | 读书 | 代码
亲,您未登录哦! 登录 | 注册

Listview中实现点击栏目标题排序

打印文章

分享到:
请看下面的代码:listview的columns属性加4个列项,viewstyle属性设为vsReport,smallimage属性对应imagelist。imagelist加载图标。query1对应与parts.db表。  

这段代码能实现升序排列,降序你稍作改动即可。如果是按字段数据类型排序则可用sql语句实现。另外这段代码可实现响应双击第一列下的图标。  

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ComCtrls, ImgList, Db, DBTables;

type
  TForm1 = class(TForm)
    ListView1: TListView;
    Button1: TButton;
    ImageList1: TImageList;
    Query1: TQuery;
    procedure Button1Click(Sender: TObject);
    procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn);
    procedure ListView1Compare(Sender: TObject; Item1, Item2: TListItem;
      Data: Integer; var Compare: Integer);
    procedure ListView1DblClick(Sender: TObject);
    procedure ListView1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    mouseX, mouseY: Integer;
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  var ColumnToSort: Integer;
implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
var
int:integer;
begin
  listview1.Items.Clear;
  int:=0;
  with query1 do
    begin
      close;
      sql.Clear;
      sql.add('select partno,description,onorder,cost from parts');
      prepare;
      open;
      first;
    end;
  while not query1.Eof do
  begin
    listView1.Items.Add.Caption:= query1.fieldbyname('partno').asstring;
    ListView1.Items.Item[int].ImageIndex:=0;
    ListView1.Items.Item[int].SubItems.Append( query1.fieldbyname('description').asstring);
    ListView1.Items.Item[int].SubItems.Append( query1.fieldbyname('onorder').asstring);
    ListView1.Items.Item[int].SubItems.Append( query1.fieldbyname('cost').asstring);
    int:=int+1;
    query1.Next;
  end;

end;


procedure TForm1.ListView1ColumnClick(Sender: TObject;
  Column: TListColumn);
begin
  ColumnToSort := Column.Index;
  (Sender as TCustomListView).AlphaSort;
end;

procedure TForm1.ListView1Compare(Sender: TObject; Item1, Item2: TListItem;
  Data: Integer; var Compare: Integer);
var
  ix: Integer;
begin
  if ColumnToSort = 0 then
    Compare := CompareText(Item1.Caption,Item2.Caption)
  else begin
   ix := ColumnToSort - 1;
   Compare := CompareText(Item1.SubItems[ix],Item2.SubItems[ix]);
  end;
end;
procedure TForm1.ListView1DblClick(Sender: TObject);
var
  Item: TListItem;
begin
  Item := ListView1.GetItemAt(mouseX, mouseY);
  if (Item <> nil) then
  begin
    beep();
    //在这可写些响应双击图标代码。
  end;
end;

procedure TForm1.ListView1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  mouseX := X;
  mouseY := Y;
end;

end.

本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( Pfan.cn )

编程爱好者论坛

本栏最新文章