Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to "delete" EMPTY LINES in a StringGrid / Grid VCL - my way >:)

emailx45

Programmer
Jan 10, 2025
8
VCL: How delete a "empty lines" in your StringGrid / Grid ?
  • a "FAKE" move up / move down lines! but a real moving...

Code:
implementation

{$R *.dfm}

type
  TMyHack = class(TStringGrid); // to access "DeleteRow()"

function MyHowManyRowsToDelete(const AStringGrid: TStringGrid): TArray<integer>;
var
  LRowText: string;
begin
  result := [];
  //
  for var i: integer := 0 to (AStringGrid.RowCount - 1) do
    begin
      LRowText := '';
      //
      for var j: integer := 0 to (AStringGrid.ColCount - 1) do
        begin
          LRowText := LRowText + AStringGrid.Cells[j, i].Trim;
          //
          if (LRowText <> '') then // to avoid still...
            break;
        end;
      //
      if LRowText.Trim = '' then // all columns is empty = row empty
        result := result + [i];
    end;
end;

procedure TForm1.BtnNormalizeRowsClick(Sender: TObject); // the main idea
var
  LRowsToDelete : TArray<integer>;
  LCurrentRowPos: integer;
begin
  // in StringGrid/Grid all cells is a string, normally!
  //
  // VisibleRowCount or RowCount = ??? = you decide!
  // StringGrid1.FixedRows = what to do with it?
  //
  LCurrentRowPos := StringGrid1.Row;
  //
  LRowsToDelete := MyHowManyRowsToDelete(StringGrid1);
  //
  if (Length(LRowsToDelete) = StringGrid1.RowCount) then // all rows empty
    begin
      StringGrid1.RowCount := 0;
      exit;
    end;
  //
  for var i: integer := high(LRowsToDelete) downto 0 do // last to first...
    TMyHack(StringGrid1).DeleteRow(LRowsToDelete[i]);   // remove it
  //
  if (LCurrentRowPos > (StringGrid1.RowCount - 1)) then
    StringGrid1.Row := StringGrid1.RowCount - 1
  else
    StringGrid1.Row := LCurrentRowPos;
end;

1736971705335.png
 

Part and Inventory Search

Sponsor

Back
Top