procedure GridDeleteRow(RowNumber: Integer; Grid: TstringGrid); var i: Integer; begin Grid.Row := RowNumber; if (Grid.Row = Grid.RowCount - 1) then { On the last row} Grid.RowCount := Grid.RowCount - 1 else begin { Not the last row} for i := RowNumber to Grid.RowCount - 1 do Grid.Rows[i] := Grid.Rows[i + 1]; Grid.RowCount := Grid.RowCount - 1; end; end;
説明:TStringGrid的爷爷TCustomGrid有DeleteRow功能、継承TCustomGrid的削除行功能{...} type TStringGridHack = class(TStringGrid) protected procedure DeleteRow(ARow: Longint); reintroduce; end; var Form1: TForm1;implementation {$R *.dfm}procedure TStringGridHack.DeleteRow(ARow: Longint); var GemRow: Integer; begin GemRow := Row; if RowCount > FixedRows + 1 then inherited DeleteRow(ARow) else Rows[ARow].Clear; if GemRow < RowCount then Row := GemRow; end; procedure TForm1.Button1Click(Sender: TObject); begin TStringGridHack(StringGrid1).DeleteRow(StringGrid1.Row); end;
这是一样的,最终也是用个for循环移动数据。 procedure TSparseList.Delete(Index: Integer); var I: Integer; begin if (Index < 0) or (Index >= FCount) then Exit; for I := Index to FCount - 1 do FList[I] := FList[I + 1]; FList[FCount] := nil; Dec(FCount); end;
var
i: Integer;
begin
Grid.Row := RowNumber;
if (Grid.Row = Grid.RowCount - 1) then
{ On the last row}
Grid.RowCount := Grid.RowCount - 1
else
begin
{ Not the last row}
for i := RowNumber to Grid.RowCount - 1 do
Grid.Rows[i] := Grid.Rows[i + 1];
Grid.RowCount := Grid.RowCount - 1;
end;
end;
源码我看了10遍以上,明确的说,没有,这已经是最高效率的了,除非不用StringGrid.
type
TStringGridHack = class(TStringGrid)
protected
procedure DeleteRow(ARow: Longint); reintroduce;
end; var
Form1: TForm1;implementation
{$R *.dfm}procedure TStringGridHack.DeleteRow(ARow: Longint);
var
GemRow: Integer;
begin
GemRow := Row;
if RowCount > FixedRows + 1 then
inherited DeleteRow(ARow)
else
Rows[ARow].Clear;
if GemRow < RowCount then Row := GemRow;
end; procedure TForm1.Button1Click(Sender: TObject);
begin
TStringGridHack(StringGrid1).DeleteRow(StringGrid1.Row);
end;
procedure TSparseList.Delete(Index: Integer);
var
I: Integer;
begin
if (Index < 0) or (Index >= FCount) then Exit;
for I := Index to FCount - 1 do
FList[I] := FList[I + 1];
FList[FCount] := nil;
Dec(FCount);
end;
用for循环吧,先清空要删除行的信息,再减少stringgrid的rowcount,就OK了