Search code examples
delphitdbgrid

When is TDBGrid.SelectedRows updated in Delphi?


I want to list some values (ID-s in this case) of the selected rows of a TDBGrid in a TEdit control.

I've tried AfterScroll event, to catch the event after(!) a selection, but it doesn't work if I use the mouse.

If I click on a row with mouse, it doesn't appear in the TDBGrid.SelectedRows collection, only after the next click/selection. If I do the selection with keyboard, everything works fine.

Do you have any idea, how to solve this?

Simplified code of my solution:

procedure TForm1.ClientDataSet1AfterScroll(DataSet: TDataSet);
begin
    edtIDs.Text := string.Join(',', GetSelectedIDs().ToArray) ;
end;

function TForm1.GetSelectedIDs() : TList<string>;
var
    i: Integer;
    ds: TDataSet;
    bmOrig: TBookmark;
begin
    FSelectedIDs.Clear();
    ds := DBGrid1.DataSource.DataSet;
    bmOrig := ds.GetBookmark();
    ds.AfterScroll := nil;                          //switch off AfterScroll event
    try
        if DBGrid1.SelectedRows.Count > 0 then begin
            for i := 0 to DBGrid1.SelectedRows.Count - 1 do begin
                ds.GotoBookmark(DBGrid1.SelectedRows.Items[i]);
                FSelectedIDs.Add(ds.FindField('ID').AsString);
            end;
            ds.GotoBookmark(bmOrig);
        end;
    finally
        ds.AfterScroll := ClientDataSet1AfterScroll; //switch on AfterScroll event
        ds.FreeBookmark(bmOrig);
    end;
    Result := FSelectedIDs;
end;

Solution

  • Replace the OnAfterScroll event of the data source by the OnColEnter event of the TDBGrid.

    Form the help of TDBGrid.OnColEnter:

    Occurs when focus moves to a new cell in the grid.

    Write an OnColEnter event handler to take specific action when a new cell has just been selected.

    Focus moves to a cell when

    • The user navigates to the cell using the keyboard. For example, when the user uses the Tab key, or the Home key.
    • The user clicks the mouse button down in the cell.
    • The SelectedField or SelectedIndex property is set.

    Read the SelectedField or SelectedIndex property to determine which cell was just entered.