Recent

Author Topic: [SOLVED]TStringGrid.SelectEditor not selecting editor when with..do is used  (Read 3414 times)

goldenfox

  • New Member
  • *
  • Posts: 47
I don't know what's wrong but using "with tstringgrid do" will not set Edit1 as editor in TStringGrid.SelectEditor.

Did I miss something here?

Please refer to my attached source.


Thanks.

« Last Edit: May 30, 2012, 10:31:28 am by goldenfox »

Zoran

  • Hero Member
  • *****
  • Posts: 1975
    • http://wiki.lazarus.freepascal.org/User:Zoran
This:
Code: [Select]
  with StringGrid1 do
  if ( aRow > 0 ) then
  begin
    Edit1.BoundsRect := CellRect(aCol,aRow);
    Edit1.Text := Cells[aCol,aRow];
    Editor := Edit1; // -- Editor is not the parameter here, but Grid's property!
  end;

does not work, because Grid has the property of same name - Editor. So, when you enclose the code in "with" block, the property name takes precedence over the method's var parameter.
Compiler understands last line as if it is "StringGrid1.Editor := Edit1;".

This works:
Code: [Select]
  if ( aRow > 0 ) then begin
    with StringGrid1 do begin
      Edit1.BoundsRect := CellRect(aCol,aRow);
      Edit1.Text := Cells[aCol,aRow];
    end;
    Editor := Edit1;
  end;

This is a nice illustration of the dangerous side effects of using "with" in object pascal. Never enclose in "with" block more than actually needed!
Use "with" with care, avoid it as much as possible.
« Last Edit: May 30, 2012, 09:24:31 am by Zoran »
Swan, ZX Spectrum emulator https://github.com/zoran-vucenovic/swan

goldenfox

  • New Member
  • *
  • Posts: 47
@Zoran: Thanks for the tip.

 

TinyPortal © 2005-2018