I have a column in my dbgrid that is based on a lookup field.
The problem is that the end user can't set a blank value for the field - they can only select values from the lookup table.
How can I allow the end user to delete or 'blank out' a value for the column?
In the appropriate TDBGrid Key event, trap for DEL. When detected, check to see if you're in the lookup column. If so, call Clear on corresponding dataset field.
Try putting a blank value in the lookup table.
Here is my code which works in Delphi XE7. The trick is to NULL the KeyField referred to by the lookup field, not the lookup field itself.
Note that it doesn't work once the dropdown box is shown e.g. when double-clicking the cell (whether dropped down or not), or if the grid's Options include dgAlwaysShowEditor. In this case, key presses are not passed to the event handler. If I get that to work as well, I'll update the code. (Any ideas???)
procedure TformMain.DBGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
LookupResultField : TField;
begin
if Key = VK_DELETE then
if TDBGrid(Sender).SelectedField.FieldKind = fkLookup then begin // if this field is a lookup field
if not (TDBGrid(Sender).DataSource.DataSet.State in [dsInsert, dsEdit]) then // if the query is not already in edit mode
TDBGrid(Sender).DataSource.DataSet.Edit;
LookupResultField := TDBGrid(Sender).DataSource.DataSet.FieldByName (TDBGrid(Sender).SelectedField.KeyFields);
LookupResultField.Clear; // set the field to NULL
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With