delphitdbgrid

Limit maximum text length of the inplace editor in TDBGrid


How can I limit the maximum text length of the inplace editor in TDBGrid? (Delphi Berlin)

The Data Type is Float.


Solution

  • The inplace editor in a TDBGrid will update its content by calling

    procedure TInplaceEdit.UpdateContents;
    begin
      Text := '';
      EditMask := Grid.GetEditMask(Grid.Col, Grid.Row);
      Text := Grid.GetEditText(Grid.Col, Grid.Row);
      MaxLength := Grid.GetEditLimit;
    end;
    

    Where GetEditMask is implemented the following way:

    function TCustomDBGrid.GetEditMask(ACol, ARow: Longint): string;
    begin
      Result := '';
      if FDatalink.Active then
      with Columns[RawToDataColumn(ACol)] do
        if Assigned(Field) then
          Result := Field.EditMask;
    end;
    

    and GetEditLimit like this:

    function TCustomDBGrid.GetEditLimit: Integer;
    begin
      Result := 0;
      if Assigned(SelectedField) and (SelectedField.DataType in [ftString, ftWideString]) then
        Result := SelectedField.Size;
    end;
    

    There you have multiple ways to get to the desired behavior I think.

    Code for approach 1 could look like this:

    // Opening of dataset
    ...
    DataSet.FieldByName('FloatField').EditMask := '00.00';
    

    This will mask will require two digits before and after the decimal seperator. See TEditMask for more on masks.

    For approach 2:

    uses
      Data.DB,
      Vcl.DBGrids;
    
    type
      TMyDBGrid = class(TDBGrid)
      protected
        function  GetEditLimit: Integer; override;
      end;
    
    implementation
    
    { TMyDBGrid }
    
    function TMyDBGrid.GetEditLimit: Integer;
    begin
      Result := inherited GetEditLimit;
      if (Result = 0) and Assigned(SelectedField) and (SelectedField.DataType = ftFloat) then
        Result := 5; // Whatever you decide
    end;
    

    Like kobik suggests, you can then use this class as interposer class. To do this, add TDBGrid = class(TMyDBGrid); in the unit you want to use that grid. If you declared TMyDBGrid in the same unit you want to use it, make the type reference clear TMyDBGrid = class(Vcl.DBGrids.TDBGrid).