Einzelnen Beitrag anzeigen

Blup

Registriert seit: 7. Aug 2008
Ort: Brandenburg
1.464 Beiträge
 
Delphi 12 Athens
 
#4

AW: Befüllen eines Stringgrids

  Alt 9. Sep 2020, 13:42
Bei TStringGrid könnte man mit Class Helper arbeiten:
Delphi-Quellcode:
  TGridRow = record
    constructor Create(AGrid: TStringGrid; ARowNum: Integer);
  private
    FGrid: TStringGrid;
    FRowNum: Integer;
    function GetColumn(const AName: string): string;
    procedure SetColumn(const AName, AValue: string);
  public
    property Column[const AName: string]: string read GetColumn write SetColumn; default;
  end;

  TColumnHelper = class helper for TStringGrid
  private
    procedure CheckRowNum(const ARowNum: Integer);
    function GetGridRow(const ARowNum: Integer): TGridRow;
  protected
    function GetColumnIndex(const AName: string): Integer;
  public
    property GridRow[const ARowNum: Integer]: TGridRow read GetGridRow;
  end;

implementation

{ TColumnHelper }

procedure TColumnHelper.CheckRowNum(const ARowNum: Integer);
begin
  if ARowNum < 1 then
    raise Exception.CreateFmt('TColumnHelper RowNum(%d) invalid < 1', [ARowNum]);

  if ARowNum >= RowCount then
    raise Exception.CreateFmt('TColumnHelper RowNum(%d) invalid >= RowCount(%d)', [ARowNum, RowCount]);
end;

function TColumnHelper.GetColumnIndex(const AName: string): Integer;
var
  i: Integer;
begin
  for i := 0 to ColCount - 1 do
  begin
    if SameText(AName, Cells[i, 0]) then
      Exit(i);
  end;
  raise Exception.CreateFmt('TColumnHelper Column[''%s''] invalid', [AName]);
end;

function TColumnHelper.GetGridRow(const ARowNum: Integer): TGridRow;
begin
  CheckRowNum(ARowNum);

  Result := TGridRow.Create(Self, ARowNum);
end;

{ TGridRow }

constructor TGridRow.Create(AGrid: TStringGrid; ARowNum: Integer);
begin
  FGrid := AGrid;
  FRowNum := ARowNum;
end;

function TGridRow.GetColumn(const AName: string): string;
begin
  Result := FGrid.Cells[FGrid.GetColumnIndex(AName), FRowNum];
end;

procedure TGridRow.SetColumn(const AName, AValue: string);
begin
  FGrid.Cells[FGrid.GetColumnIndex(AName), FRowNum] := AValue;
end;
Delphi-Quellcode:
var
  lRow: TGridRow;
begin
  StringGrid1.Cells[0,0] := 'Zeile';
  StringGrid1.Cells[1,0] := 'Name';
  StringGrid1.Cells[2,0] := 'Ort';
  StringGrid1.Cells[3,0] := 'Tel.';

  StringGrid1.GridRow[1]['Zeile'] := '1';
  StringGrid1.GridRow[1]['Name'] := 'Hans';
  StringGrid1.GridRow[1]['Ort'] := 'Ort1';
  StringGrid1.GridRow[1]['Tel.'] := '000/00001';

  lRow := StringGrid1.GridRow[2];
  lRow['Zeile'] := '2';
  lRow['Name'] := 'Otto';
  lRow['Ort'] := 'Ort2';
  lRow['Tel.'] := '000/00002';
end;
  Mit Zitat antworten Zitat