Avatar of LeTay
LeTay
 asked on

Force position in a TStringGrid

After having filled in a TStringGrid programmatically, I want to force a specific row, say row N, to be "selected"
How can I achieve that
Delphi

Avatar of undefined
Last Comment
LeTay

8/22/2022 - Mon
jimyX

Make sure to set the following options of the StringGrid from the OI:
goRangeSelect = False
goRowSelect = True

Use OnSelectCell event to test for the current select row if it matches your target row then allow select, otherwise CanSelect equals False:
//Set the current selected row:
procedure TForm1.FormCreate(Sender: TObject);
begin
  StringGrid1.Row:= N;
end;

procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,
  ARow: Integer; var CanSelect: Boolean);
begin
  CanSelect:= False;

  //list the allowed rows to be selected
  if ARow = N then
    CanSelect:= True;
end;

Open in new window

LeTay

ASKER
Ok
If now I use StringGrid1.Row = something somewhere in my code, does that forces the selectcell event automatically ?
jimyX

As you can see, at OnSelectCell event there is "N", where the comparison takes place to either allow or deny selecting rows, so it all depends on what you assign to this "N".
So no, it will not be automatically, you need to assign value to the "N" variable every time you need to update the selected row(s).

If you need other solution, it would be disable the entire StringGrid after selecting the row, unless you need to do some work on it, in this case you need to restrict selection by OnSelectCell event.
Your help has saved me hundreds of hours of internet surfing.
fblack61
LeTay

ASKER
Well, not sure to have explained exactly what I needed.
When the form is displayed, the TStringGrid is filled in (from database data).
The "selected" row is the first one below the titles.
User click on another row, that row becomes the selected one.
At that time, the user can do some action, and after that action, I refresh completely the TStringGrid (clear and filled in again)
How can I then, at that precise time, have that previously select row (says row N), become the selected (and highlighted) one ?
ASKER CERTIFIED SOLUTION
jimyX

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
LeTay

ASKER
Many thanks