最近在玩单机版的游戏《钢铁雄心2》,写了一个编辑将领技能的小咚咚,里面用到stringgrid的排序,上网翻了一遍,然后自己写了一个,简单用delphi自带的Tlist的排序功能,不用自己写排序程序:
//StringGrid排序(乌龙哈里20090417,delphi2007+winxp sp3)
procedure GridSort(Grid: TStringGrid; Ascend: Boolean);
type
TMyArr=record
No:integer;
StrData:string;
end;
PMyArr=^TMyArr;
function MySort(item1,item2:PMyArr):integer; //排序函数
begin
Result:=CompareText(item1.StrData,item2.StrData);
end; var
i:integer;
List:Tlist;
MyArr:PMyArr;
GridRow:TStrings;
begin
GridRow:=TStringList.Create;
List:=TList.Create;
for i := 1 to Grid.RowCount-1 do //倒入排序数据
begin
New(MyArr);
MyArr^.No:=i;
MyArr^.StrData:=Grid.Cells[Grid.Col,i];
List.Add(MyArr);
GridRow.Add(Grid.Rows[i].Text);
end;
List.Sort(@MySort); //调用排序函数排序
for I := 0 to List.Count - 1 do
begin
MyArr:=List.Items[i];
if Ascend then //往grid里面重写排好序的数据
begin
Grid.Rows[i+1].Text:=(GridRow[MyArr^.No-1]);
Grid.Cells[0,i+1]:=inttostr(i+1);
end else
begin
Grid.Rows[LeaderNum-i].Text:=(GridRow[MyArr^.No-1]);
Grid.Cells[0,LeaderNum-i]:=inttostr(LeaderNum-i);
end;
Dispose(MyArr);
end;
List.Free;
GridRow.Free;
end;
我是在stringgrid右键popup菜单中调用该函数,下面是popup菜单:
procedure TForm1.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if button=mbRight then
PopupMenu1.Popup(mouse.CursorPos.X,mouse.CursorPos.Y);
end;
=========
ps:那个代码框真难看,改成直接贴了