简体   繁体   中英

Display Password Char for editable TField in DBGrid

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM