I just know I'm doing something really silly here, but I don't seem to be able to nut it out.

I'm having a first attempt at colouring a cell's background in a DBGrid, something I've avoided up until now. I have a field called "Buttoncolour" which holds a hex colour in the form "CCFFCC". I have another column, the one I want to colour, called "ColourDescription". I want to use the hex colour code to colour the canvas of the "ColourDescription" cell.

I have this code:

 procedure TProductForm.MDBGrid2DrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TDBGColumn;
  State: TGridDrawState);
var
   CCol : String;
begin
   if column.fieldname = 'ColourDescription' then begin
      CCol := ProdGroupQuery.FieldByName('Buttoncolour').AsString;
      Canvas.Brush.Color:= StringToColor(CCol);
   end;
end;

I get a compile error telling me that something is not an integer value. I assume that I've just got the whole thing wrong. Can any of you kind people tell me what I SHOULD be doing, please?

Thanks!

有帮助吗?

解决方案

Your string is hex encoded. In order for StringToColor to decode that, you must prefix the string with a $ symbol.

Canvas.Brush.Color := StringToColor('$'+CCol);

This is made clear in the documentation which is always worth reading when you get stuck.

It may be simpler to call StrToInt instead of StringToColor since StringToColor does more than you need.

Canvas.Brush.Color := TColor(StrToInt('$'+CCol));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top