Uses the multi-selection: OnSelectionChange
to enable an action only while rows are selected, and SelectedRowIds
to apply it to each selected record.
The user selects several products (Ctrl+click on Windows; on Android
a tap on a row’s gutter, then taps on the other rows) and presses
Deactivate, which clears the Active field
of each selected product.
// FormCreate
Grid1.Options := Grid1.Options + [egoMultiSelect];
BtnDeactivate.Enabled := False;
Besides EgFireGrid: EgFireGrid.RowSource
(TEgFireGridRowId), Data.DB
(TBookmark), System.SysUtils
(Format) and the unit of the dataset component (here
FireDAC.Comp.Client, for Query1).
procedure TForm1.Grid1SelectionChange(Sender: TObject);
begin
BtnDeactivate.Enabled := Grid1.SelectedRowCount > 0;
BtnDeactivate.Text := Format('Deactivate (%d)', [Grid1.SelectedRowCount]);
end;
procedure TForm1.BtnDeactivateClick(Sender: TObject);
var
Ids: TArray<TEgFireGridRowId>;
Id: TEgFireGridRowId;
Saved: TBookmark;
begin
Ids := Grid1.SelectedRowIds;
Saved := Query1.GetBookmark;
Query1.DisableControls;
try
for Id in Ids do
if Grid1.RowSource.GotoRowId(Id) then
begin
Query1.Edit;
Query1.FieldByName('Active').AsBoolean := False;
Query1.Post;
end;
if Query1.BookmarkValid(Saved) then
Query1.GotoBookmark(Saved);
finally
Query1.FreeBookmark(Saved);
Query1.EnableControls;
end;
Grid1.ClearSelection;
end;
RowSource.GotoRowId makes the
row of an identity the current record.SelectedRowIds drops deleted rows: a
record deleted since it was selected is left out, and
GotoRowId returns False for one deleted
meanwhile.DisableControls keeps the grid from
redrawing at every record, and the current record is restored at the
end.