Sunday, November 24, 2019

Coloring the TDBGrid Delphi Component

Coloring the TDBGrid Delphi Component Adding color to your database grids will enhance the appearance and differentiate the importance of certain rows or columns within the database. Well do this by focusing on DBGrid, which provides a great user interface tool for displaying data. Well assume that you already know how to connect a database to a DBGrid component. The easiest way to accomplish this is to use the Database Form Wizard. Select the employee.db from the DBDemos alias and select all fields except EmpNo. Coloring Columns The first and easiest thing you can do to visually enhance the user interface is to color individual columns in the data-aware grid. Well accomplish this through the TColumns property of the grid. Select the grid component in the form and invoke the Columns editor by double-clicking the grids Columns property in the Object Inspector. The only thing left to do is specify the background color of the cells for any particular column. For text  foreground color, see the font property. Tip: For more information on Columns editor, look for Columns editor: creating persistent columns in your Delphi help files. Coloring Rows If you want to color the selected row in a DBGrid but you dont want to use the dgRowSelect option (because you want to be able to edit the data), you should instead use the DBGrid.OnDrawColumnCell event. This technique demonstrates how to dynamically change the color of text in a DBGrid: procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);beginif Table1.FieldByName(Salary).AsCurrency36000 then DBGrid1.Canvas.Font.Color:clMaroon;DBGrid1.DefaultDrawColumnCell (Rect, DataCol, Column, State);end; Heres how to dynamically change the color of  a row in a DBGrid: procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);beginif Table1.FieldByName(Salary).AsCurrency36000 then DBGrid1.Canvas.Brush.Color:clWhite;DBGrid1.DefaultDrawColumnCell (Rect, DataCol, Column, State);end; Coloring Cells Finally, heres how to change the background color of the cells of any particular column, plus the text foreground color: procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);beginif Table1.FieldByName(Salary).AsCurrency40000 thenbegin DBGrid1.Canvas.Font.Color:clWhite; DBGrid1.Canvas.Brush.Color:clBlack;end;if DataCol 4 then //4 th column is Salary DBGrid1.DefaultDrawColumnCell (Rect, DataCol, Column, State);end; As you can see, if an employees salary is greater than 40 thousand, its Salary cell is displayed in black and the text is displayed in white.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.