systemgvp
systemgvp

Reputation: 41

Lazarus TStringGrid - Color a cell

Problem. I have two TStringGrids on the same Form. When I click on a cell (x, y) of the first Table, the background of the same cell (x, y) of the second table must turn red. How can I do since the tables are different?

I know how to find a cell using the OnClick method on table1, but I don't know how to color a cell in table2

Upvotes: 2

Views: 2097

Answers (2)

Dsm
Dsm

Reputation: 6013

You must tell grid2 somehow which cell(s) you want highlighted. There are many ways to do this, depending on what you want to do.

If you just want the last cell clicked highlighted create a couple of form variables, say fx and fy and set them in your onclick event and refresh grid2. Then use the following OnDraw event for grid 2.

procedure TFormAdobeTest.StringGrid2DrawCell(Sender: TObject; ACol,
  ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  if (ACol = fx) and (ACol =fy) then
  begin
    StringGrid2.Canvas.Brush.Color := clRed;
    StringGrid2.Canvas.Rectangle( Rect );
  end
  else
  begin
    StringGrid2.Canvas.Brush.Color := clWhite;
    StringGrid2.Canvas.Rectangle( Rect );
  end;
end;

Obviously this could be extended of you want all clicked boxes recorded. Another way to do this is to instead use the objects property to tell StringGrid2 to pass this information for example by assigning StringGrid1 to the objects property (or any other object!)

an then the routine become

procedure TFormAdobeTest.StringGrid2DrawCell(Sender: TObject; ACol,
  ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  if Assigned( StringGrid2.Objects [ ACol, ARow]) then
  begin
    StringGrid2.Canvas.Brush.Color := clRed;
    StringGrid2.Canvas.Rectangle( Rect );
  end
  else
  begin
    StringGrid2.Canvas.Brush.Color := clWhite;
    StringGrid2.Canvas.Rectangle( Rect );
  end;
end;

These are just a starting point of course.

Upvotes: 3

systemgvp
systemgvp

Reputation: 41

Thanks, I have achieved part of my purpose with this:

procedure TForm1.StringGrid1Click(Sender: TObject);
begin
  if (StringGrid1.col > 0) and (StringGrid1.row > 0) then
  begin
    cc := StringGrid1.col;
    rr := StringGrid1.row;
  end
  else
  begin
    cc := -1;
    rr := -1;
  end;
  memo1.Lines.Append(cc.ToString+','+rr.ToString);
  StringGrid2.Repaint;
end;

procedure TForm1.StringGrid2DrawCell(Sender: TObject; aCol, aRow: Integer;
  aRect: TRect; aState: TGridDrawState);
begin
  if (ACol = cc) and (aRow = rr) then
  begin
    StringGrid2.Canvas.Brush.Color := clRed;
    StringGrid2.Canvas.Rectangle(aRect);
  end;
end; 

   

enter image description here

Upvotes: 1

Related Questions