Programmatically highlight a stringgrid row
Asked Answered
M

1

5

i have a string grid in Delphi 7, with 0..N rows. There is a listbox with numbers from 0..N if the user clicks on the any number in the listbox number , that row number should be selected on the stringgrid.

so i have this

   MystringGrid.Col :=0;
   MystringGrid.Row :=Listbox.itemindex;
   MystringGrid.Selection:=TGridRect(Rect(0,1 ,1 ,1));
   MystringGrid.SetFocus;

This will nicely select the row on the grid (highlight it) but the problem is if

 listbox.itemindex=MystringGrid.rowcount;

That time i get

 Grid Index out of range error 

as in grids.pas

 if (ACol < 0) or (ARow < 0) or (ACol >= ColCount) or (ARow >= RowCount) then
  InvalidOp(SIndexOutOfRange)

(ARow >= RowCount) is true so error

how do i select the last row?

Manganese answered 6/4, 2013 at 13:4 Comment(1)
Off by one or fencepost errors, as we call them, are a PEBKAC problem. Problem exists between keyboard and chair. I.E., your human brain is off by one, not the computer.Clubhaul
B
7

If there are 3 rows, then they are called

0,  1,  2.

Notice that there is no row called 3.

More generally, if there are N rows, then they are called

0,  1,  2, ..., N - 1.

Notice that there is no row called N.

Hence, your problem can be found already on the first line of your question:

i [sic!] have a string grid in Delphi 7, with N rows. There is a listbox with numbers from 0..N

If there are N rows, then the listbox should contain the numbers 0..N-1. Indeed, if you let it contain the numbers 0..N, then the number of lines in the listbox will equal N+1, i.e., one more than the number of items in the string grid.

Also: I'd do simply

StringGrid1.Selection := TGridRect(Rect(0, 3, 4, 3))

to select the row with index 3, assuming the number of columns is 4+1

Berth answered 6/4, 2013 at 13:6 Comment(2)
(i changed 0..n in question ) ok thats correct :)..but the thing is if i select 1 in the listbox..the 1st row is selected. The listbox and the grid has equal number of rows. the only problem is for the last row when i click on the last row of the listbox, the grid index out of range error comes as grids.pas raise errorManganese
@psqluser: Your selection code is weird, too. I'd do simply StringGrid1.Selection := TGridRect(Rect(0, 3, 4, 3)) to select the row with index 3, assuming the number of columns is 4+1.Berth

© 2022 - 2024 — McMap. All rights reserved.