Edit and Display Boolean Fields using a CheckBox in Delphi's DBGrid

Tip submitted by Rene van der Heijden

A series of articles titled Adding components to a DBGrid discusses placing just about any Delphi control (visual component) into a cell of a DGBrid. The idea is to create visually more attractive user interfaces for editing fields inside a DBGrid: a ComboBox for drop down lists; a DateTimePicker (calendar) for date values; a check box for boolean fields.

CheckBox for Boolean Fields

The article CheckBox inside a DBGrid provides one method of using a check box control to edit and display values for boolean fields.

As noticed by Rene van der Heijden the solution is rather lengthy, and it doesn't work, at least not when using the mouse to click on the checkboxes.

Rene suggest an easier approach needing only two even handlers: OnCellClick and OnCustomDrawCell for your DBGrid control:

 //OnCellClik event of a DBGrid1
 procedure TForm.DBGrid1CellClick(Column: TColumn) ;
   if (Column.Field.DataType=ftBoolean) then
     {toggle True and False}
     Column.Field.Value:= not Column.Field.AsBoolean;
    {immediate post - see for yourself whether you want this}
     {you may add additional functionality here,    to be processed after the change was made}
 //OnDrawColumnCell event of a DBGrid1
 procedure TForm.DBGrid1DrawColumnCell(
   Sender: TObject;
   const Rect: TRect;
   DataCol: Integer;
   Column: TColumn;
   State: TGridDrawState) ;
   CtrlState: array[Boolean] of integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED) ;
   if (Column.Field.DataType=ftBoolean) then
     DBGrid1.Canvas.FillRect(Rect) ;
     if VarIsNull(Column.Field.Value) then
       DrawFrameControl(DBGrid1.Canvas.Handle,Rect, DFC_BUTTON, DFCS_BUTTONCHECK or DFCS_INACTIVE) {grayed}
       DrawFrameControl(DBGrid1.Canvas.Handle,Rect, DFC_BUTTON, CtrlState[Column.Field.AsBoolean]) ; {checked or unchecked}

Delphi tips navigator:
» Remove Duplicate Items in Delphi's TStringList
« 5 Facts you Did Not Know about Delphi and Classes and the VCL and Inheritance and Custom Controls and...