Alex Rivera | Logout

How to modify a cell value in Delphi TDBGrid

Asked 2012-09-19T15:47:11.300
8

I have to display some modified 'masked' value in a VCL TDBGrid (Delphi XE2), ie : change 'password' to 'xxxxxxxx' or uppercase 'pass' to 'PASS' or others. As my Fields are dynamically created (but the Name is coded so I know how and when mask them ie : xxxx_PASSW for password Fields) I can't use (I Think) OnGetText event.

So what is the most efficient way to do this (as I yet use OnDrawColumnCell for some presentation modification I would prefere to use it) ?

Edit
Report

1 Answer

12

There are at least 3 ways to do this, I'll illustrate by masking a password field from a database. I'm using sql server for the sql dialect.

1. Define a calculated field on the sql string.

select field1, field2, '********' as maskedPwd from table1;

Then, right-click on the dbgrid, choose the columns editor. Inside the columns editor of the dbgrid, simply select maskedPwd column instead of the real password column. Now the dbgrid will display the masked value instead of the password.

or

2. Define a calculated field on the dataset used by the dbgrid.

Simply right-click on the dataset, and use the fields-editor to create a new calculated field (e.g. maskedPwd2). Then onCalcField event of the dataset, write code to set the value of maskedPwd2, i.e.

procedure TForm1.ADOQuery1CalcFields(DataSet: TDataSet);
begin
  DataSet.FieldByName('maskedPwd2').AsString := '********';
end;

Make sure to include maskedPwd2 in the column editor of the dbgrid.

or

3. Write custom text on the onDrawColumnCell event of the dbgrid.

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  grid : TDBGrid;
  maskValue : String;
  aRect : TRect;
begin
  maskValue := '********';
  aRect := Rect;
  grid := sender as TDBGrid;

  if column.FieldName = 'password' then
  begin
    grid.Canvas.FillRect(Rect);
    DrawText(grid.Canvas.Handle, PChar(maskValue), Length(maskValue), aRect,
      DT_SINGLELINE or DT_LEFT or DT_VCENTER);
  end;
end;

Note that the code above only displaying the masked value, but if the grid is editable, the real password value will be visible when the cell is focused/edited.

To deal with this, drop a TEdit on the form, clear the text property, set Ppass

answered 2012-09-21T04:32:47.650

Your Answer