سؤال

I am having some issues with a piece of code I wrote. I am using a TStringGrid to draw a seating plan.

What it is supposed to do is label the fixedcol and fixedrow with the letter down the column and numbers for the rows.

My problem is i don't know how to change my code so that it excludes the cell [0,0]. It is also not labeling all the rows.

procedure TfrmDraw.FormCreate(Sender: TObject);
var
  i, j, k: Integer;
begin
  sgFloor.RowCount := adotSeats['Rows'] + 1;
  sgFloor.ColCount := adotSeats['Seats_per_Row'] + 1;

  for i := 0 to SgFloor.RowCount do 
  begin
    for j := 0 to SgFloor.ColCount do
    begin
      if i = 0 then
        SgFloor.Cells[i,j] := Chr(65 + j)
      else
      if j = 0 then
      begin
        for k := 1 to sgFloor.ColCount do
          SgFloor.Cells[i,0] := IntToStr(i) ;
      end;
    end;
  end;
end;

Screenshot:

enter image description here

Thanks

هل كانت مفيدة؟

المحلول

Some good advice:

I know how easy it is to use the RAD style components, but try not to bind GUI logic and application logic. This will make your code cleaner and easier to read and maintain. Also use meaningful names for your variables, doing this will prevent stupid mistakes.

Now about your problem, the Grid uses 0-based indexes so the last Index is one less as the count. The fixed row and column both have Index 0 in your case which means we have to start iterating from the next index, which is 1, I used the FixedRows and FixedCols properties to make it more readable. This has the added bonus that it will label the most inner fixed Rows/Cols if you have more than one Fixed row/column. It is easier to make 2 separate loops, one for the header row and one for the columns :

procedure SetupGrid(Grid : TStringGrid; Rows, Columns : Integer);

var
 Row, Col: Integer;

begin
 Grid.FixedCols := 1;
 Grid.FixedRows := 1;
 Grid.RowCount := Rows + Grid.FixedRows;
 Grid.ColCount := Columns + Grid.FixedCols;

 for Row := Grid.FixedRows to Grid.RowCount-1 do 
  Grid.Cells[0, Row] := Chr(Ord('A') + Row-1);

 for Col := Grid.FixedCols to Grid.ColCount-1 do
  Grid.Cells[Col, 0] := IntToStr(Col); 
end;

procedure TfrmDraw.FormCreate(Sender: TObject);
begin
 // try to make your GUI events as lightweight as possible and seal
 // your code into separate functions/classes, this will improve readability 
 // of the GUI units and it will make your code testable
 SetupGrid(sgFloor, adotSeats['Rows'], adotSeats['Seats_per_Row']);  
end;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top