Question

Well, some kind of n00b question from me. I've surfed the net and similar questions here but haven't found any right answers for such simple (as I thought) problem.

I have a DBGrid. I select one row and make some actions with another data linked to this row. After I finished, my DBGrid being refreshed and selected row resets to first. I want to get the same row selected that was selected before refreshing DBGrid data. Any suggestions?

Was it helpful?

Solution

Before refreshing, save the linked dataset's current selection as a bookmark, then restore the bookmark afterwards.

OTHER TIPS

This answer is intended as a minor supplement to Mason's, not an alternative. I've added it only because another answer has appeared, suggesting, incorrectly imo, the use of the dataset's RecNo property. Not all TDataSet descendants implement RecNo reliably or at all. Some descendants just return a constant value e.g. 0 for the current rows's RecNo and do nothing when you assign a value to it.

procedure TMyForm.DoSomethingWithDataSet(ADataSet : TDataSet);
var
  Bookmark : TBookmark;
begin
  Bookmark := ADataSet.GetBookmark; // Save your place in ADataSet

  try
    Screen.Cursor := crSqlWait;  // Show the user that something is happening
    Update;  // update the form to make sure screen cursor updates
    ADataSet.DisableControls;
    // do something with ADataSet here  e.g.
    ADataSet.First;
    while not ADataSet.Eof do begin
      // do something with current row here, then
      ADataSet.Next;
    end;
  finally
    ADataSet.GotoBookmark(Bookmark);  // Return to where you were at outset
    ADataSet.FreeBookmark(Bookmark);
    ADataSet.EnableControls;
    Screen.Cursor := crDefault;  // Let the user see you're done
  end;
end;
RecKey:=DmFRM.ViewTBL.RecNo;
          with DmFRM.ViewTBL do
               begin
                  Active:=false;
                  Active:=True;
                  RecNo:=RecKey;
               end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top