How to change line color of a DBGrid in Delphi?

Question:

I'm making an expense control system, and when registering a new income or new expense I want it to change the color of the line of that register in the dbGrid as chosen, I used a TDBRadioGroup to choose between 'Expense' and 'Income' . How would the code look?

Answer:

In your database there should be a field where you inform if the amount is an expense or income. Let's say the name of this field is called 'type' . You can change the colors like this:

Two clicks on your DBGrid 's onDrawColumnCell event

    If tabelaTIPO.Value = 'despesa' then // condição
      begin
      Dbgrid1.Canvas.Font.Color:= clRed; // coloque aqui a cor desejada
      Dbgrid1.DefaultDrawDataCell(Rect, dbgrid1.columns[datacol].field, State);
      end else
      begin
      Dbgrid1.Canvas.Font.Color:= clGreen; // coloque aqui a cor desejada
      Dbgrid1.DefaultDrawDataCell(Rect, dbgrid1.columns[datacol].field, State);
      end;

What the code does is check if the TYPE field of your table is 'expense', it paints red, otherwise it paints green. But you can choose any color you like.

In the example I cited, I made a condition using a string to make it easier, but I recommend using an integer field 0 for expense and 1 for income.

Scroll to Top