【发布时间】:2023-04-06 11:06:01
【问题描述】:
因此,我在此处提到的程序中的字符串网格:(Delphi - Changing active page's tab color and having it reset after clicking on another tab) 从最小到最大完美排序,但网格在某种程度上出现故障/失控。已排序的行被扔到网格的末尾(有时甚至没有行号或行保留它们的编号)。所以我的问题是如何在不完全破坏网格的情况下对字符串网格进行排序?
我正在使用的代码:
//code that sorts the grid
procedure TfrmPuntehou.SortSTLGrid(var grid:TStringGrid; columntotal:integer);
const
separator = ',';
var
iCount,i,j,k,iPos:integer;
TheList:TStringList;
sString,sTempString:string;
begin
//procedure to sort from small to large values
//get row amount
iCount:=grid.RowCount;
//create list
TheList:=TStringList.Create;
TheList.Sorted:=False;
//start of try..finally block
try
begin
//fill the list
for i := 1 to (iCount - 1) do
begin
TheList.Add(grid.Rows[i].Strings[columntotal]+separator+grid.Rows[i].Text);
end;
//sort the list
TheList.Sort;
for k := 1 to TheList.Count do
begin
//take the line of the list and put it in a string var
sString:= TheList.Strings[(k-1)];
//get separator pos in that string
iPos:=AnsiPos(separator,sString);
sTempString:='';
//remove separator and the column text at the front of the string
sTempString:=Copy(sString,(iPos+2),Length(sString));
TheList.Strings[(k-1)]:= '';
TheList.Strings[(k-1)]:= sTempString;
end;
//fill the grid
for j:= 1 to (iCount - 1) do
begin
grid.Rows[j].Text := TheList.Strings[(J-1)] ;
end;
end;
finally
TheList.Free;
end;
//end of try..finally block
end;
//code that I use to customize the grid on startup
procedure TfrmPuntehou.TitlesAndNumbering(grid: TStringGrid);
var
i:integer;
begin
//procedure that customizes the grid entered as a parameter
with grid do
begin
//names the columns
Cells[0,0]:='Row Number';
Cells[1,0]:='Car Number';
Cells[2,0]:='Name';
Cells[3,0]:='Licence';
Cells[4,0]:='Heat 1';
Cells[5,0]:='Heat 2';
Cells[6,0]:='Subtotal 1';
Cells[7,0]:='Heat 3';
Cells[8,0]:='Subtotal 2';
Cells[9,0]:='Final';
Cells[10,0]:='Final Total';
//for loop to number the rows
for i := 1 to rowMax do
begin
Cells[0,i]:=IntToStr(i);
end;
//end of for
//other extra settings
RowCount:=rowMax;
ColCount:=colMax;
DefaultColWidth:=100;
FixedCols:=0;
FixedRows:=1;
end;
end;
说明问题的屏幕截图:
提前感谢您的帮助!
亲切的问候
PrimeBeat
【问题讨论】:
-
如果我理解正确,除了左列的行号之外,您有许多空行,因为您将 RowCount 设置为 RowMax。排序后,空单元格将位于列表顶部。你为什么要在未排序的网格底部保持这样的空行(排序后到达顶部)?如果要保留这些行,则必须更改用于排序的比较函数,以使空字符串大于所有其他字符串,从而使它们保持在底部。
-
好吧,我想如果我在启动时将行数设置为 40,通过提前生成所有行,可以更轻松地将信息插入行。是否可以将数据插入网格的行而无需设置特定的行数或最大行数类型的东西?因为我认为它会使排序等变得容易得多。
-
@PrimeBeat 是的,可以随时更改行数。只需添加一些按钮,允许用户“添加”或“删除”一行。当然,您需要添加代码才能真正做到这一点????
-
另一方面,您也可以跳过将“空”行添加到排序字符串列表,然后,在读取数据时,只需在网格行数超过字符串列表计数时停止,然后只写入将空字符串写入网格,而不是排序列表中的数据。
标签: sorting delphi delphi-xe2 tstringgrid