Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select row after refreshing DBGrid

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?

like image 406
Vlad Avatar asked Oct 25 '09 11:10

Vlad


2 Answers

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

like image 175
Mason Wheeler Avatar answered Oct 09 '22 08:10

Mason Wheeler


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;
like image 43
MartynA Avatar answered Oct 09 '22 07:10

MartynA