首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除StringGrid中的行- Delphi

删除StringGrid中的行- Delphi
EN

Stack Overflow用户
提问于 2013-12-06 21:28:06
回答 2查看 10.6K关注 0票数 3

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

代码语言:javascript
复制
    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;

请找人帮忙。:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-07 17:50:57

可以检索所选行的StringGrid1.selected,并且可以调用以下过程。

代码语言:javascript
复制
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;
票数 1
EN

Stack Overflow用户

发布于 2013-12-07 00:47:06

如果您正在使用标准的VCL (没有使用最近版本中提供的活动绑定),那么可以使用TStringGrid类来访问受保护的TCustomGrid.DeleteRow方法。

下面的代码已经在Delphi2007中进行了测试。它使用一个放在表单上的简单TStringGrid,具有默认的列和单元格,以及一个标准TButton

TForm.OnCreate事件处理程序只是用一些数据填充网格,以便更容易地看到已删除的行。每次单击时,按钮单击事件都会从字符串网格中删除第1行。

注意::代码不进行错误检查以确保有足够的行。这是一个演示应用程序,不是生产代码的示例。您的实际代码应该在尝试删除行数之前检查可用行数。

代码语言:javascript
复制
// 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20425121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档