Re: StringGrid to Edit.Text

Posted by webmaster Guido on October 10, 2007

In Reply to Re: StringGrid to EditText problem posted by Milsdam on October 09, 2007

: If at first you don't succeed, try, try, try again.
: Found it myself afterall
: procedure TForm1.DownClick(Sender: TObject);
: var
: Row : integer;
: begin
:
: if StringGrid1.Row < StringGrid1.RowCount -1 then
: StringGrid1.Row := StringGrid1.Row +1
: else
: Beep;
: for Row := 0 to StringGrid1.Row do begin
: Edit1.Text := StringGrid1.Cells[0,Row];
: Edit2.Text := StringGrid1.Cells[1,Row];
: Edit3.Text := StringGrid1.Cells[2,Row];
: Edit4.Text := StringGrid1.Cells[3,Row];
: end;
: end;
:
: Thanks anyway

The error in the code of your previous message didn't work, because you didn't put anything in the variable Row. To make it less confusing, because you have two items called "Row" that are totally different, let's change the first name to R:

procedure TForm1.DownClick(Sender: TObject);
var 
  R: Integer;
begin
  if StringGrid1.Row < StringGrid1.RowCount -1 then
    StringGrid1.Row := StringGrid1.Row +1
  else
    Beep;
  // R is still empty at this point, but
  // in the next line you add 1 to it: 
  R := R + 1;
  // What's the value of R at this point...?
  Edit1.Text := StringGrid1.Cells[0, R];  
  Edit2.Text := StringGrid1.Cells[1, R];
  Edit3.Text := StringGrid1.Cells[2, R];
  Edit4.Text := StringGrid1.Cells[3, R];
end;

Your newer code works because in the for...next loop you put a value in Row. But in fact you don't need the for...next, look at this example:

procedure TForm1.DownClick(Sender: TObject);
var
  R: integer;
begin
  if StringGrid1.Row < StringGrid1.RowCount - 1 then
    StringGrid1.Row := StringGrid1.Row + 1
  else
    Beep;
  R := StringGrid1.Row;
  Edit1.Text := StringGrid1.Cells[0, R];
  Edit2.Text := StringGrid1.Cells[1, R];
  Edit3.Text := StringGrid1.Cells[2, R];
  Edit4.Text := StringGrid1.Cells[3, R];  
end;

...and in fact, we even don't need the variable R ;)
Let's rewrite everything in the most readable way:

procedure TForm1.DownClick(Sender: TObject);
begin
  if StringGrid1.Row < StringGrid1.RowCount - 1 then begin
    StringGrid1.Row := StringGrid1.Row + 1;
    Edit1.Text := StringGrid1.Cells[0, StringGrid1.Row];
    Edit2.Text := StringGrid1.Cells[1, StringGrid1.Row];
    Edit3.Text := StringGrid1.Cells[2, StringGrid1.Row];
    Edit4.Text := StringGrid1.Cells[3, StringGrid1.Row];  
  end
  else
    Beep;

Good luck!
webmaster Guido

Follow Ups