0

I am testing the TDictionary using the embarcadero sample ( http://docwiki.embarcadero.com/CodeExamples/XE5/en/Generics_Collections_TDictionary_%28Delphi%29 )

No problem for creating and adding key and value. However, when I try to access the table using key value 'London':

(1) Dictionary.Items['London'].Country -> gives the correct value "Dictionary.Items['London'].Country'

(2) input 'London' in Edit1.Text, then Dictionary.Items[Edit1.Text].Country -> gives error "the item not found'?

Could someone explain this?

Thanks in advance.

//////////////////////////////////// /// sample code

var Dictionary: TDictionary<String, TCity>;
    City, Value: TCity;
    Key: String;


begin
  Dictionary := TDictionary<String, TCity>.Create;
  City := TCity.Create;
  { Add some key-value pairs to the dictionary. }
  City.Country := 'Romania';
  City.Latitude := 47.16;
  City.Longitude := 27.58;
  Dictionary.Add('Iasi', City);

  City := TCity.Create;
  City.Country := 'United Kingdom';
  City.Latitude := 51.5;
  City.Longitude := -0.17;
  Dictionary.Add('London', City);

  City := TCity.Create;
  City.Country := 'Argentina';
  { Notice the wrong coordinates }
  City.Latitude := 0;
  City.Longitude := 0;
  Dictionary.Add('Buenos Aires', City);

  showmessage(Dictionary.Items['London'].Country); // This One is OK

  // now using Edit1.Text where I put 'London'
  Showmessage(Dictionary.Items[Edit1.Text].Country); // This return to error message (Item not found)


  Dictionary.Clear;
  Dictionary.Free;
  City.Free;

end;

1 Answers1

1

The explanation is that, contrary to what you claim, Edit1.Text does not equal 'London'. Perhaps the letter case does not match. Or there is leading or trailing whitespace.

Add an assertion to verify that I am correct:

Assert(Edit1.Text='London');
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490