Deleting a selected row via mouse click in TStringGrid using delphi

4.1k views Asked by At

I'm not sure how i would capture the row selected by a mouse click and then press a button to delete that selected row in a stringGrid in delphi.

procedure DeleteRow(Grid: TStringGrid; ARow: Integer);
var
  i: Integer;
begin
  for i := ARow to Grid.RowCount - 2 do
    Grid.Rows[i].Assign(Grid.Rows[i + 1]);
  Grid.RowCount := Grid.RowCount - 1;
end;

procedure TManageUsersForm.RemoveRowButtonClick(Sender: TObject);
var
  Recordposition : integer;
begin
  UserStringGrid.Options := UserStringGrid.Options + [goEditing];
  UserStringGrid.Options := UserStringGrid.Options + [goRowSelect];
end;

So the first procedure is for deleting a row and the second makes sure when a user clicks a cell the whole row is highlighted not just that 1 cell.

The mouse click is the most important part!!

Thank You :)

2

There are 2 answers

0
Sertac Akyuz On BEST ANSWER

The mouse click is not the most important part. Users can select a row either by keyboard or mouse, it doesn't matter, you'd just want to delete the current row. In the case of a mouse click, or otherwise, you can get the current row by Row.

procedure DeleteCurrentRow(Grid: TStringGrid);
var
  i: Integer;
begin
  for i := Grid.Row to Grid.RowCount - 2 do
    Grid.Rows[i].Assign(Grid.Rows[i + 1]);
  Grid.RowCount := Grid.RowCount - 1;
end;

Call it like;

DeleteCurrentRow(UserStringGrid);
0
MartynA On

I imagine the problem you might be having is to work out which grid row the user has clicked on. One way is:

procedure TForm1.StringGrid1Click(Sender: TObject);
var
  StringGrid : TStringGrid;
  Row : Integer;
  GridRect : TGridRect;
begin
  // The Sender argument to StringGrid1Click is actually the StringGrid itself,
  // and the following "as" cast lets you assign it to the StringGrid local variable
  // in a "type-safe" way, and access its properties and methods via the temporary variable
  StringGrid := Sender as TStringGrid;

  // Now we can retrieve the use selection
  GridRect := StringGrid.Selection;

  // and hence the related GridRect
  // btw, the value returned for Row automatically takes account of
  // the number of FixedRows, if any, of the grid
  Row := GridRect.Top;

  Caption := IntToStr(Row);
  { ...}
end;

See the OLH about TGridRect.

Hopefully the above will be sufficient to get you going - you've obvious already got most of the way yourself. Or, you could try the method suggested in the other answer, which is a little more "direct" but this way might be a bit more instructive as a "how to". Your choice ...