filipe26,
DBGrid provides a SelectedRows property, which is a list of TBookmarks back into the underlying DataSet. You can walk through this to obtain the underlying field values and then assign those to a query or filter string as needed.
Here are a couple of examples taken froma quick demo application I threw together. It's based on the DBDEMOS database provided with Delphi, but the underlying techniques should apply to any tDataset descendant.
First, here's one way to assemble the key values from the SelectedRows into asingle string variable. (The idea might be to use this to change a filter string:
Code:
procedure TfrmMainData.DBGrid1CellClick(Column: TColumn);
var
str : String; // temporary storage
si : SmallInt; // loop counter
begin
with DBGrid1 do
begin
if SelectedRows.Count > 0 then
begin
str := '';
With DataSource.DataSet do
for si := 0 to SelectedRows.Count - 1 do
begin
GotoBookmark( pointer( SelectedRows.Items[ si ] ) );
str := str + FieldByName( 'CustNo' ).asString + ', ';
end;
str := copy( str, 1, length( str ) - 2 );
Edit1.Text := str;
end;
end;
end;
In this case, we create a comma-delimited string containing the selected key values and throw that in an Edit box. You can use this in whatever way you want.
As I said, it's basic, but it shows one way to do it.
Alternatively, you can also assemble the kay values into StringLists, as shown in this example. Once the key values have been captured, their used to dynamically generate an appropriate SQL query.
Code:
procedure TfrmMainData.Button1Click(Sender: TObject);
var
si : SmallInt; // loop counter
sl : tStringList; // temporary storage
begin
sl := tStringList.Create;
try
// First, get the selected ID Values.
with sl, dbGrid1, DataSource.DataSet do
if SelectedRows.Count > 0 then
begin
add( 'where' );
for si := 0 to SelectedRows.Count - 1 do
begin
GotoBookMark( pointer( SelectedRows.Items[ si ] ) );
add( 'o.CustNo = ' +
fieldByName( 'CustNo' ).asString );
if si < SelectedRows.Count - 1 then
add( ' OR ' );
end;
end;
// Now, revise the query
with dmMainData.Query1 do
begin
if active then close;
SQL.clear;
SQL.add( 'select distinct * from orders o' );
SQL.AddStrings( sl );
Open;
end;
finally
freeAndNil( sl );
end;
end;
Again, it's relatively trivial. And, yes, it's example--not production--code. (My typical production code isn't
quite this sloppy; I was in a hurry.)
Still, I hope it helps...
-- Lance