Einzelnen Beitrag anzeigen

Nogge

Registriert seit: 15. Jul 2004
336 Beiträge
 
Delphi 7 Professional
 
#18

Re: StringGrid - Aktuelle Zeile löschen

  Alt 26. Jul 2007, 18:54
Ich habe mir mal selbst add- und delete-Methoden für TStringGrid geschrieben, die so, wie folgt, meiner Meinung nach objekt-orientiert implementiert sind:
Delphi-Quellcode:
{
  @author
          Nogge
  @description
          TStringGridEx extends TStringGrid with two methods, which based on
          methods and properties of TStringGrid. So TStringGridEx can easily be
          used as type-cast class without creating an instance of it.
            - addRow
                  Adds a new row to the end of the StringGrid and fills a
                  specific string in each column
            - deleteRow
                  Clears the content of each column of the row specified by an
                  index and, if applicable, deletes it from the StringGrid
}

unit StringGridEx;

interface

uses Grids, SysUtils;

type
  EListError = class(Exception);

  TStringGridEx = class(TStringGrid)
  public
    function addRow(const VCols: array of String): Integer;
    (* HINT for reintroduce:
        - overrides virtual method of TCustomGrid
        - changes access right from protected to public
    *)

    procedure deleteRow(ARow: Longint); reintroduce;
  end;

implementation

function TStringGridEx.addRow(const VCols: array of String): Integer;
var
  i: Integer;
begin
  // catch exception
  if (Length(VCols) > ColCount) then
    raise EListError.CreateFmt('Col index out of bounds (%d)', [High(VCols)])
  else
  begin
    // execute code
    if (Length(Cells[0, FixedRows]) = 0) then // wenn kein Zeichen enthalten ist
    begin
      for i := Low(VCols) to High(VCols) do
        Cells[i, FixedRows] := VCols[i];
    end
    else
    begin
      RowCount := RowCount +1;
      for i := Low(VCols) to High(VCols) do
        Cells[i, RowCount-1] := VCols[i];
    end;
    Result := RowCount -1;
  end;
end;

(*
    Clears all entries (Strings[] AND Objects[]) of the specific row
*)

procedure TStringGridEx.deleteRow(ARow: Longint);
begin
  // FixedRows should not be deleted
  if (ARow < FixedRows) or (ARow >= RowCount) then
  begin
    raise EListError.CreateFmt('Row index out of bounds (%d)', [ARow]);
  end
  else
  begin
    if (RowCount-1 > FixedRows) then
      inherited DeleteRow(ARow)
    else // FixedRows is always less than RowCount
      Rows[FixedRows].Clear;
  end;
end;
Verwendungsbeispiel:
Delphi-Quellcode:
uses: [...], StringGridEx;
[...]
// als einfacher Aufruf...
TStringGridEx(StringGrid1).deleteRow(2);
// ...oder als Methode
procedure DeleteRow(sg: TStringGrid; index: Integer);
begin
  TStringGridEx(sg).deleteRow(index);
end;
Hierdurch werden alle public-Methoden und Properties der Klasse TStringGrid sowie die beiden zusätzlichen public-Methoden von TStringGridEx zur Verfügung gestellt, ohne das private-Methoden und Attribute sichtbar werden.
  Mit Zitat antworten Zitat