0
votes

I have a TStringGrid with several rows in which I implemented some kind of 'read-only' row. More exactly, I don't allow the user to click the penultimate row. If the user clicks the last row nothing happens; the focus won't be moved to the cells of that row.

I have the code (in KeyDown) and everything works smooth. However, if the user clicks the top row and then uses the mouse wheel to scroll down, eventually the focus will move to the penultimate row. Any idea how to prevent this?

2
To answer your question, how to prevent it... Simply fix your code, since behavior you've described is different from a default behavior of a string grid without any event handling. The grid row selection is changed while you're scrolling but by one row per scroll step, not from the first row to the penultimate one (except when you'd have 3 rows of course :-)TLama
@TLama - I never said that it will jump from the first row to the last. If the user keeps scrolling it will eventually reach the last row :)External Server Error
Well, so then I didn't get the part, if the user clicks the top row and then uses the mouse wheel to scroll down, the focus will move to the penultimate row. Any idea how to prevent this ? It sounds like it's happening to you and you want to prevent that behavior.TLama
@TLama - No.... sorry for confusion. I added 'eventually' in the OP.External Server Error
A point of clarification: "penultimate" means "next-to-last", not last. Your question is saying that focus shouldn't change to the second-last row. You mean the last row, right?Graham

2 Answers

5
votes

Well, you could override DoMouseWheelDown to achieve this.

function TMyStringGrid.DoMouseWheelDown(Shift: TShiftState; 
  MousePos: TPoint): Boolean;
begin
  if Row<RowCount-2 then
    //only allow wheel down if we are above the penultimate row
    Result := inherited DoMouseWheelDown(Shift, MousePos)
  else
    Result := False;
end;

But how do you know that there isn't some other way to move the focus to the last row?

In fact a much better solution is to override SelectCell:

function TMyStringGrid.SelectCell(ACol, ARow: Longint): Boolean;
begin
  Result := ARow<RowCount-1;
end;

When you do it this way you don't need any KeyDown code, and you don't need to override DoMouseWheelDown. All possible mechanisms to change the selected cell to the final row will be blocked by this.

As @TLama correctly points out, you don't need to sub-class TStringGrid to achieve this. You can use the OnSelectCell event:

procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Longint;
  var CanSelect: Boolean);
begin
  CanSelect := ARow<(Sender as TStringGrid).RowCount-1;
end;
-1
votes

I solved this problem by putting this in the event OnMouseWheelUp:

procedure Tmainform.sgup(Sender: TObject; Shift: TShiftState;
  MousePos: TPoint; var Handled: Boolean);
begin
        sg.RowCount := sg.RowCount + 1;
        sg.RowCount := sg.RowCount - 1;
end;