IceCold
IceCold

Reputation: 21231

How do I prevent the scroll wheel from selecting the last row of a TStringGrid?

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?

Upvotes: 0

Views: 4778

Answers (2)

Alberto Vazquez
Alberto Vazquez

Reputation: 1

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;

Upvotes: -1

David Heffernan
David Heffernan

Reputation: 613572

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;

Upvotes: 5

Related Questions