如果您使用的是标准 VCL TStringGrid
(不使用最新版本中提供的实时绑定),则可以使用插入器类来访问受保护的TCustomGrid.DeleteRow
方法。
下面的代码已经在 Delphi 2007 中进行了测试。它使用一个简单的TStringGrid
拖放到表单上,具有默认的列和单元格,以及一个标准的TButton
.
事件TForm.OnCreate
处理程序只是用一些数据填充网格,以便更容易查看已删除的行。每次单击按钮单击事件时,都会从 stringgrid 中删除第 1 行。
注意:代码不进行错误检查以确保有足够的行。这是一个演示应用程序,而不是生产代码的示例。您的实际代码应在尝试删除行之前检查可用行数。
// Interposer class, named to indicate it's use
type
THackGrid=class(TCustomGrid);
// Populates stringgrid with test data for clarity
procedure TForm1.FormCreate(Sender: TObject);
var
i, j: Integer;
begin
for i := 1 to StringGrid1.ColCount - 1 do
StringGrid1.Cells[i, 0] := Format('Col %d', [i]);
for j := 1 to StringGrid1.RowCount - 1 do
begin
StringGrid1.Cells[0, j] := Format('Row #d', [j]);
for i := 1 to StringGrid1.ColCount - 1 do
begin
StringGrid1.Cells[i, j] := Format('C: %d R: %d', [i, j]);
end;
end;
end;
// Deletes row 1 from the stringgrid every time it's clicked
// See note above for info about lack of error checking code.
procedure TForm1.Button1Click(Sender: TObject);
begin
THackGrid(StringGrid1).DeleteRow(1);
end;
如果您使用的是更新的版本,并且已使用实时绑定将数据附加到网格,您只需从基础数据中删除该行并让实时绑定处理删除该行。