Question

I'm using Locate method to search in TADOTable, but it's not work with multiple field search. (I'm searching directly on the TADOTable, therefore Not interested with SQL in this case).

The following code works fine when using single field, but does not work with multiple fields!

void __fastcall TForm1::Button1Click(TObject *Sender)
{
        TLocateOptions LOpts;
        LOpts.Clear();
        LOpts << loPartialKey;
        Variant VAR[1];
        VAR[0] = Variant(Edit1->Text);

        try{
          if ( ADOTable1->Locate("CompanyID;Supplier", VAR, LOpts) ){
            // Record found
          }
        }
        catch(...){}
}
Was it helpful?

Solution

Searching for multiple fields in a TADODataSet is done pretty much the same as with any other TDataSet, using the Locate function and an optional TLocateOptions:

if ADODataSet1.Locate('CompanyID;Supplier', 
                      VarArrayOf([Edit1.Text, Edit2.Text]), 
                      [loPartialKey]) then
begin
  // Record found
end;

As your comment indicates you're actually using C++Builder and TADOTable, here's an example that works for it as well (compiled and tested under C++Builder XE5 in a new VCL Forms application):

TLocateOptions Opts;
Opts.Clear();
Opts << loPartialKey;

Variant locateValues[2];
locateValues[0] = Variant(Edit1->Text);
locateValues[1] = Variant(Edit2->Text);

if (ADOTable1->Locate("CompanyID;Supplier", VarArrayOf(locateValues, 1), Opts))
{
  // Record found.
};

Your comment to the original question indicates that what you actually want is to search two columns to see if either of them match a value. You can't do that with a single Locate, but you can do it with multiple calls (Delphi code - you should be able to easily convert it to C++ Builder given the other samples here). Of course, both columns would have to be the same data type - you can't search a numeric field and a character field for the same numeric (or character) value without converting something:

var
  LastName: Variant;
begin
  LastName := Edit1.Text;
  if ADOTable1.Locate('LastName', LastName, [loPartialKey]) or
     ADOTable1.Locate('CompanyName', LastName, [loPartialKey]) then
  begin
    // Record found
  end;

The other alternative is to use a Filter (again, Delphi code - straightforward C++ Builder translation):

AdoTable1.Filter := 'LastName = ' + QuotedStr(Edit1.Text) +
                    ' or CompanyName LIKE "' + QuotedStr(Edit1.Text) + '%"';
AdoTable1.Filtered := True;
AdoTable1.First;
// Get key values needed to locate on a full key, and then clear the filter.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top