Monday, September 12, 2011

Delete Row or Column in a TStringGrid

Create a Form and put an StringGrid on it
add this procedure on your form

procedure RemoveRowColStringGrid(StringGrid: TStringGrid;
  RowCol: boolean; Which: integer);
var
  i: integer;
begin
  if RowCol= True then
  begin
    for i := StringGrid.Row to StringGrid.RowCount - 1 do
    begin
      StringGrid.Rows[i] := StringGrid.Rows[i + 1];
    end;
    StringGrid.RowCount := StringGrid.RowCount - 1;
  end
  else
  begin
    for i := StringGrid.Col to StringGrid.ColCount - 1 do
    begin
      StringGrid.Cols[i] := StringGrid.Cols[i + 1];
    end;
    StringGrid.ColCount := StringGrid.ColCount - 1;
  end;
end;
In this example we will use the event OnKeyDown of StringGrid
procedure Form1.StringGrid1.KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if key = VK_DELETE then //if key is delete
begin
  RemoveRowColStringGrid(
"Your StringGrid",
"True to remove row, False to remove col",
"Index of the row you want to remove");
end;
end;