Frage

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?

War es hilfreich?

Lösung

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;

Andere Tipps

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;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top