Matt Biggs
Matt Biggs

Reputation: 177

Loops and increasing letter values for cells in string grid

So this could be hard to explain but i want to do a for ... := 1 to 10 do statement but i want it to be for A to N do. The main purpose of this excersise is to load data into a string grid. So lets have it load the cells 0,1 0,2 0,3 0,4 0,5 0,6 0,7 with the Letter A, B, C, D, E all the way up to 14. If anyone knows how to do this i would be extremely thankful!

Upvotes: 0

Views: 2108

Answers (3)

Arioch 'The
Arioch 'The

Reputation: 16045

Want to fuse TLama's answer with that "want to do a for ... := 1 to 10 do statement but i want it to be for A to N do"

Don't know if it will be pun, or enlightening.

var c: char; i: integer;
    s: string;  
    ...
  i := 0; s:= EmptyStr;
  for c := 'A' to 'N' do begin
      s := s + c + ',';
      Inc(i);
  end;

  SetLength(s, Length(s) - 1); // we do not need last comma there
  StringGrid1.ColCount := i;
  StringGrid1.Rows[0].CommaText := s;

Or the same using TStringBuilder - which would be faster than re-arranging Heap on each new string modification.

uses SysUtils;
    ...
var c: char; i: integer;
    s: string;
    ...
  i := 0;
  with TStringBuilder.Create do try
     for c := 'A' to 'N' do begin
         Append(c + ',');
         Inc(i);
     end;
     s := ToString;
  finally 
     Free;
  end;

  SetLength(s, Length(s) - 1); // we do not need last comma there
  StringGrid1.ColCount := i;
  StringGrid1.Rows[0].CommaText := s;

Upvotes: 0

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

If you want to fill the StringGrid control one row at a time, you can do

procedure TForm1.Button1Click(Sender: TObject);
var
  i: Integer;
begin
  StringGrid1.FixedCols := 1;
  StringGrid1.FixedRows := 1;
  for i := 0 to Min(25, (StringGrid1.ColCount-1) * (StringGrid1.RowCount-1)) do
    StringGrid1.Cells[i mod (StringGrid1.ColCount - 1) + 1,
      i div (StringGrid1.ColCount - 1) + 1] := Chr(Ord('A') + i);
end;

which works no matter how many rows and cols there are.

Upvotes: 1

TLama
TLama

Reputation: 76693

Here you got it, but I'm not sure if it's a good way how to learn programming (I mean asking question as requests so that someone else write code for you):

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
begin
  StringGrid1.FixedCols := 1;
  StringGrid1.ColCount := 15;
  for I := 1 to 14 do
    StringGrid1.Cells[I, 1] := Chr(Ord('A') + I - 1);
end;

Upvotes: 6

Related Questions