Color Cell in a stringgrid

Problem: we want to color a cell inside a TStringGrid. No easy direct way in doing this in Delphi.

Solution: we must implement stringgrid’s onDrawCell event

Create a new VCL application project. Put one TButton named btnColor and one TStringGrid named strngrd1. See the screenshot below for the placement:

delphi color cell in a stringgrid form design

This is the complete Unit1.dfm source code (so you can match the options for each components in the form):


Full form source code below (Unit1.pas):


  1. We have declared 3 public variables for this form i.e. selectedRow, selectedCol, colorCell. selectedRow and selectedCol are used for application to decide which cell that will be colored. colorCell is just a controller variable that will decide whether the stringgrid cell will be colored or not.
  2. In Form1 FormCreate event, we set colorCell to False, so, when the form is created an shown, the cell will not be colored.
  3. In btnColor onClick event, we select cell in row 1 and column 1 that will be colored. We also set the colorCell variable to True so the application know what he must done. Next we call Repaint method of strngrd1 so all cells will be re-drawn.
  4. in strngrd1 onDrawCell event, we check whether we should color the cell or not. Then check if the will-be-drawn cell is the same as stated in selectedCol and selectedRow. If True, then we defined to use red brush and then color the cell background with it using FillRect method. Then we also re-draw the text written in there (if any) using TextRect. Lastly, we draw focus rectangle (DrawFocusRect)  only if the current cell is selected by user.

This is our form result:

Our delphi color cell in stringgrid form result

That’s it. Now you know the concept behind coloring a cell in TStringGrid. If you want to color multiple cell and maintain the status (colored or not and in what color), I suggest you create some TList record variable to store this and onDrawCell will iterate through this list.

Leave a Reply

%d bloggers like this: