Display Password Char for editable TField in DBGrid

2.1k views Asked by At

I have a DBGrid where I am using following query to get the data:

Select * from table1 where <condition>

One of the fields in Password coming from database, which I want to display as ***. But keep it editable for the Grid itself.

Can you please suggest what can be done for this. Sample code will be much appreciated

1

There are 1 answers

1
Andy_D On BEST ANSWER

You can do this by dropping a TEdit on your form and set the password char property to be '*'. Then you need to add code into the OnDrawColumnCell event of the TDBGrid like this :-

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 if gdfocused in State then begin Edit1.Left := Rect.Left + grid.Left + 1; Edit1.Top := rect.Top + grid.Top + 1; Edit1.Width := Rect.Right - Rect.Left + 2; Edit1.Height := Rect.Bottom - Rect.Top + 2; Edit1.Clear; Edit1.Visible := True; end else begin grid.Canvas.FillRect(Rect); DrawText(grid.Canvas.Handle, PChar(maskValue), Length(maskValue), aRect, DT_SINGLELINE or DT_LEFT or DT_VCENTER); end else grid.DefaultDrawColumnCell(Rect, DataCol, Column, state); end;

procedure TForm1.DBGrid1ColExit(Sender: TObject); begin Edit1.Visible := False; end;

procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char); begin if Key = Chr(9) then Exit;

if (Sender as TDBGrid).SelectedField.FieldName = 'password' then begin Edit1.SetFocus; SendMessage(Edit1.Handle, WM_CHAR, word(Key), 0); end; end;

procedure TForm1.Edit1Change(Sender: TObject); begin if DBGrid1.DataSource.State in [dsEdit, dsInsert] then DBGrid1.DataSource.DataSet.FieldByName('password').AsString := Edit1.Text; end;

procedure TForm1.Edit1Enter(Sender: TObject); begin DBGrid1.DataSource.Edit; end;

This should get you going, but as has been mentioned it's not ideal to be editing passwords in this way.