删除StringGrid中的行-Delphi
我想做那样的东西。我的StringGrid中有一个列表,我想通过选择单元格然后单击按钮删除一行。然后,该列表应在StringGrid中再次显示,而不显示此行。我在删除行时遇到的最大问题是,我尝试了一个过程,但它只删除了StringGrid中的行,而不是列表中的行删除StringGrid中的行-Delphi,delphi,stringgrid,Delphi,Stringgrid,我想做那样的东西。我的StringGrid中有一个列表,我想通过选择单元格然后单击按钮删除一行。然后,该列表应在StringGrid中再次显示,而不显示此行。我在删除行时遇到的最大问题是,我尝试了一个过程,但它只删除了StringGrid中的行,而不是列表中的行 procedure DeleteRow(Grid: TStringGrid; ARow: Integer); var i: Integer; begin for i := ARow to Grid.RowCount -
procedure DeleteRow(Grid: TStringGrid; ARow: Integer);
var
i: Integer;
begin
for i := ARow to Grid.RowCount - 2 do
Grid.Rows[i].Assign(Grid.Rows[i + 1]);
Grid.RowCount := Grid.RowCount - 1;
end;
请找个人帮忙。:) 如果您使用的是标准VCL
TStringGrid
(不使用最新版本中提供的实时绑定),则可以使用插入器类访问受保护的TCustomGrid.DeleteRow
方法
以下代码已经在Delphi2007中进行了测试。它使用一个简单的TStringGrid
拖放到表单上,带有默认的列和单元格,以及一个标准的TButton
TForm.OnCreate
事件处理程序只是用一些数据填充网格,以便更容易查看删除的行。button click事件每次单击时都会从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;
如果您使用的是较新的版本,并且使用实时绑定将数据附加到网格,则只需从基础数据中删除该行,并让实时绑定处理删除该行的操作。可以检索所选行
StringGrid1。所选行,您可以调用以下过程
procedure TUtils.DeleteRow(ARowIndex: Integer; AGrid: TStringGrid);
var
i, j: Integer;
begin
with AGrid do
begin
if (ARowIndex = RowCount) then
RowCount := RowCount - 1
else
begin
for i := ARowIndex to RowCount do
for j := 0 to ColumnCount do
Cells[j, i] := Cells[j, i + 1];
RowCount := RowCount - 1;
end;
end;
end;
我不确定我是否理解正确,但在我看来,你有两个结构,一个列表和一个网格。您显示的代码将从网格中删除一行。是什么阻止您从列表中删除相应的项?所以我应该一次性从列表和网格中删除该项?我没有想到这一点……如果您使用实时绑定在网格中显示列表,您可以从列表中删除该项。或者,调用TStringGrid.DeleteRow()
方法。它被声明为受保护的,但您可以使用访问器类来访问它:键入TStringGridAccess=class(TStringGrid)end;TStringGridAccess(AGrid).DeleteRow(arovindex)代码>