Thursday, November 26, 2026

Editing check boxes in a DBGrid - revised

A year and a half ago, I wrote about editing check boxes in a DBGrid1; this was in 'the good old days' of Delphi 7 and dbExpress components. I had occasion to revisit a unit that used this code and found that it didn't work with Delphi 12CE and FireDAC, primarily because the grid was buffered with a memtable. After working with CoPilot on a solution and then working alone to improve that solution, I now present a new approach to editing check boxes in a DBGrid. Apart from anything else, this code also prevents the 0 and 1 that would appear using the old solution.

First, two clarifications to the previous code: there is no need to define columns in the grid, and the dgEditing flag in the grid's options should not be set. Thus there's no possibility of changing a value in a text field. The check box's value is changed by simply clicking on the check box: this is handled in the OnCellClick method of the grid. The check at the beginning if sametext (fn, 'finance') prevents anything bad happening if the user clicks on a field that is not drawn as a checkbox. The sametext function fixes any problems that might occur if one parameter is in upper case and another is in lower case (or in CamelCode format). 

procedure TShowContact2Cust.DBGrid1CellClick(Column: TColumn); var fn: string; begin fn:= DBGrid1.SelectedField.FieldName; if sametext (fn, 'finance') or sametext (fn, 'report') or sametext (fn, 'miyun') or sametext (fn, 'call') then begin ToggleCheckBox (dbgrid1.selectedfield); qUpdate.macrobyname ('fieldname').asraw:= fn; qUpdate.params[0].asinteger:= mtContact2CustID.asinteger; qUpdate.execsql; dbGrid1.EditorMode:= false; end; end;

qUpdate is required in this form as the grid's dataset is a memtable; in another form there is no memtable sitting between the database and the grid and so qUpdate is not required there. This query uses a macro, thus enabling it to update any one of the four fields without having to manipulate the query's text.

update contact2cust set !fieldname = 1 - !fieldname where id = :p1;

The ToggleCheckBox procedure is very simple and uses a trick that avoids having to test whether the parameter belongs to a memtable or a query.

Procedure ToggleCheckBox (sf: tfield); begin sf.DataSet.Edit; sf.AsInteger:= 1 - sf.AsInteger; sf.DataSet.Post; end;

And that's all the code that is necessary. Much simpler than what went before.

Internal links
[1] 1935



This day in blog history:

Blog # Date Title Tags
1443 26/11/2021 Opening Excel from a thread and displaying a file Programming, Delphi, Office automation, Threads
1690 26/11/2023 Guitar thoughts Guitars
1866 26/11/2024 Delphi logging Programming, Delphi

No comments: