Wanted - string grid code that highlights a clicked column

I want to let users click on the top of a column in a string grid and colour the column light green so they can clearly see where they are. I have code that does this but will not show any text in the light green column. I have tried a couple of ways to display text using textout in the CellDraw event handler but the text is still obliterated by the light green rectangle from CellDraw.

Can someone please show me what to change so that the grid will have a coloured column that lets me correctly display the text that is entered.

My code is shown below, the form has a string grid on it with goEditing set to true.

var
  Form1: TForm1;
  whichColumn : integer;

implementation

{$R *.DFM}

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
//paint non fixed cells in one column in light green
//the column is chosen in the MouseDown event handler
begin
        if (acol = whichColumn) and (arow <> 0) and (acol <> 0) then
        begin
             StringGrid1.canvas.brush.Color := $0080FF80;
             StringGrid1.canvas.fillRect(rect);
        end
end;

procedure TForm1.StringGrid1MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
//respond to click on one of the fixed cells in the top row
//by finding which column was clicked then repainting the grid
var
    tempX : integer;
begin
    if (y < StringGrid1.RowHeights[0]) and (x > StringGrid1.ColWidths[0]) then
    //in top row, not in column zero
    begin
        tempX := x - StringGrid1.ColWidths[0];
        whichColumn := StringGrid1.LeftCol - 1;
        //now reduce tempX by the column widths until it is zero or less
        //which will tell us which column the click happened in
        while tempX > 0 do
        begin
            tempX := tempX - StringGrid1.ColWidths[whichColumn];
            inc(whichColumn);
        end;
        //When we repaint the DrawCell event handler will draw
        //the chosen column in light green
        StringGrid1.Repaint;
    end;
end;

seabearAsked:
Who is Participating?
 
philipleighsConnect With a Mentor Commented:
After these lines:

StringGrid1.canvas.brush.Color := $0080FF80;
             StringGrid1.canvas.fillRect(rect);

why don't you just call TextOut?

             StringGrid1.canvas.TextOut(Rect.Left + 2, Rect.Top + 2, StringGrid1.Cells[ACol, ARow]);

Cheers,
Phil.
0
All Courses

From novice to tech pro — start learning today.