Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allow a blank value on a lookup field in a TDBGrid?

Tags:

delphi

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?

like image 752
croceldon Avatar asked Sep 30 '09 18:09

croceldon


3 Answers

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.

like image 178
Larry Lustig Avatar answered Sep 22 '22 20:09

Larry Lustig


Try putting a blank value in the lookup table.

like image 34
Mason Wheeler Avatar answered Sep 23 '22 20:09

Mason Wheeler


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;
like image 21
Reversed Engineer Avatar answered Sep 24 '22 20:09

Reversed Engineer