Search code examples
visual-foxpro

How to get record data from locate?


In VFP 6 I have a table called "cars" and inside a button I want to find an ID based on the name. What did I do wrong?

... code
SELECT cars
LOCATE FOR ALLTRIM(UPPER(name)) = variable_read_from_textbox 
IF NOT FOUND()
  messagebox("not found")
ELSE
  messagebox(cars.id_car)
ENDIF

Running the code works ok when the name is not found but when it is found it errors out.

Thanks!


Solution

  • Your code is right in general. Slight modification for safety and fix for error:

    SELECT cars
    * this implies an exact match, regardless of set exact, and makes casing same
    * remember this wouldn't use an index unless there is an index with the same signature 
    LOCATE FOR ALLTRIM(UPPER(name)) == ALLTRIM(UPPER(m.variable_read_from_textbox))
    
    IF NOT FOUND()
      messagebox("not found")
    ELSE
      messagebox(transform(cars.id_car))
    ENDIF
    

    As far as I remember, in VFP6, messagebox() was not yet capable transforming the value to string for you and expects a string (you didn't tell what the error is but that should be it).

    A little caution about your search.

    ALLTRIM(UPPER(name))
    

    will NOT use an index, unless there is an index with key "ALLTRIM(UPPER(name))". If there is, it would be used, but such an index is actually useless because of the alltrim(). A better index would simply be:

    Upper(name)
    

    and then your search would look like:

    variable_read_from_textbox = ALLTRIM(UPPER(m.variable_read_from_textbox))
    
    SET EXACT ON 
    SELECT cars
    LOCATE FOR UPPER(name) = m.variable_read_from_textbox 
    IF NOT FOUND()
     ...