mohammadreza hosseini
mohammadreza hosseini

Reputation: 11

Retrieving the values of a specific column in a TDBGrid

I have a TDBGRID called Grid in my application with 3 columns:

EMP_ID    EMP_FirstName    EMP_LastName

My grid is multiselect.

How can I get the EMP_ID of the selected rows when the user clicks a button (I want to pass them to a stored procedure).

Upvotes: 1

Views: 2914

Answers (1)

MartynA
MartynA

Reputation: 30745

If I understand what you would like, the code below should help.

The rows in a DBGrid which are selected are recorded in bookmarks stored in its SelectedRows property. So, to get a list of the procedure TForm1.GetBookmarkIDs, what you need to do is:

  • Save your current position in the grid (CDS1.GetBookmark)

  • Iterate the SelectedRows' items to get each bookmark in turn, get the bookmark, get the dataset to go to that bookmark and get the EMP_ID for the dataset row (in my test data, the column name happens to be just 'ID').

  • Do whatever you like with the EMP_ID value

  • Return to the record we bookmarked at the start

The calls to DisableControls and EnableControls are to speed things up as they prevent other data-aware controls in the GUI (as well as the grid, of course) from being updated while the selected rows are visited.

Code:

procedure TForm1.GetBookmarkIDs;
var
  BM,
  SelectedBM : TBookmark;
  EMP_ID : Integer;
  i : Integer;
begin
   BM := CDS1.GetBookmark;
   try
     CDS1.DisableControls;
     CDS1.First;
     for i  := 0 to DBGrid1.SelectedRows.Count - 1 do begin
       SelectedBM := PChar(DBGrid1.SelectedRows[i]);
       CDS1.GotoBookmark(SelectedBM);
       EMP_ID := CDS1.FieldByName('ID').AsInteger;
       Memo1.Lines.Add(IntToStr(EMP_ID));
     end;
   finally
     CDS1.GotoBookmark(BM);
     CDS1.FreeBookmark(BM);
     CDS1.EnableControls;
   end;
 end;

You didn't say exactly how you need to format your list of EMP_IDs to send to the stored procedure. With the above code, you would do something like call the Stored Proc each time around the "for i := 0 ..." loop.

If you wanted them, say, as a comma-delimited list, you could rewrite the routine as a function returning a string, along these lines

function TForm1.GetBookmarkIDs : String;
[...]
begin
  Result := '';
  [...]
       //EMP_ID := CDS1.FieldByName('ID').AsInteger;
       if Result <> '' then
         Result := Result + ', ';
       Result := Result + CDS1.FieldByName('ID').AsString;
       [...]

Upvotes: 1

Related Questions