【问题标题】:Delete row in StringGrid- Delphi在 StringGrid-Delphi 中删除行
【发布时间】:2013-12-06 13:28:06
【问题描述】:

我想做这样的东西。我的 StringGrid 中有一个列表,我想通过选择单元格然后单击按钮来删除一行。然后这个列表应该在没有这一行的 StringGrid 中再次显示。我在删除行时遇到的最大问题是,我尝试了一个过程,但它只删除了 StringGrid 中的行,而不是列表中的行,我想。

    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;

请人帮忙。 :)

【问题讨论】:

  • 我不确定我是否理解正确,但在我看来,您有两个结构,一个列表和一个网格。您提供的代码从网格中删除了一行。是什么阻止您从列表中删除相应的项目?
  • 所以我应该一次性从列表和网格中删除项目?没想到……
  • 如果您使用实时绑定在网格中显示列表,您可以从列表中删除该项目。

标签: delphi stringgrid


【解决方案1】:

如果您使用标准 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;

如果您使用的是更新的版本,并已使用实时绑定将数据附加到网格,您只需从基础数据中删除该行并让实时绑定处理删除该行。

【讨论】:

    【解决方案2】:

    可以检索选定的行StringGrid1.selected,您可以调用以下过程。

    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() 方法。它被声明为protected,但您可以使用访问器类来访问它:type TStringGridAccess = class(TStringGrid) end; TStringGridAccess(AGrid).DeleteRow(ARowIndex);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    相关资源
    最近更新 更多