Return no records if FIndKey results in False?

1.9k views Asked by At

Using TDataSet.FindKey you can locate records. When it results in True the datasets cursor will be positioned on the found record.
I use this when I select items in a list on the left, corresponding data should appear on the right.
When it results in False the cursor is not moved. This results in the record data prior to FindKey being displayed in data aware components on the right.

How can I code the result of FindKey to return an empty record?

    if Not tblSomeTable.FindKey([SomeSearchData]) then
    begin
        < code to return empty or move data cursor to neutral position >
    end;

Update: (Waited a few days before selecting right answer as I believe that is the custom and didn't wan to discourage further feedback.) There were several suggestions on tackling this situation although I believe the correct answer was from Marcelo in that it is not possible to have a cursor not be on a record. Several workarounds were suggested. I chose one of my own. It went something like:

    If Not tblSomeTable.FindKey([SomeSearchData]) then
    begin
        tblSomeTable.FindKey([-1,2010]);
    end

What I did is create a dummy, blank record with an index that the actual data can never be, ie: The first index value will never be -1. If the initial search comes up empty then the FindKey will position the cursor on this empty record. This will provide the visual effect I was after.

3

There are 3 answers

0
Marcelo Cantos On BEST ANSWER

This is not possible as far as I know. The cursor must always be on a record unless Bof and Eof are both true (empty data set).

0
Heinz Z. On

Hallo,

use SetRange instead of FindKey.

tblSomeTable.SetRange([SomeSearchData],[SomeSearchData]);
try
  while not tblSomeTable.Eof do begin
    <do something with the Record>
    tblSomeTable.Next;
  end;
finally
  tblSomeTable.CanelRange;
end;

when you criteria ensures that the maximum of matching records is one you retrieve with the statement above zero or one record.

0
da-soft On

TDataSet does not have a "neutral position". But as always you have few options:

  1. Set dataset into insert / append record mode. So, the controls and code will see empty record. Be careful, as something may incidentally assign data to a field and then the new record may be posted to DB.
  2. Depending on the data access components, you are using, you can set dataset to Cached Updates mode, insert and post new empty record into dataset, and mark all changes as applied. Then assign a filter, normally rejecting this empty record. Then in your code you have to switch the filter over, so it will reject all records, excluding this empty one.
  3. Consider to disconnect the TDataSource from the dataset and later connect it again.

Note sure, but probably there may be invented some other approaches :)