c++builder-6

Cannot convert 'AnsiString' to 'TPicture *' in C++ Builder 6


So I was trying to replace the picture used in a TImage component, but I was not able to compile the program. Here is the code:

void __fastcall TFrame2::Button1Click(TObject *Sender)
{
 if (userPictureDialog->Execute()) {
  try
  {
   Form1->userPicture->Picture = userPictureDialog->FileName;
  }
  catch (...)
  {
   ShowMessage("There was an error while opening the file.");
  }
 }
}

What should I do to fix this?


Solution

  • A TPicture is a wrapper for binary graphic data, not a string. Even if it were, you are trying to assign an AnsiString to a TPicture* pointer, not to a TPicture object. There are no operator= defined for those kinds of conversions, hence the compiler error.

    Since your string is a path to a graphic file on disk, you need to call the TPicture::LoadFromFile() method instead, eg:

    void __fastcall TFrame2::Button1Click(TObject *Sender)
    {
      if (userPictureDialog->Execute()) {
        try
        {
          Form1->userPicture->Picture->LoadFromFile(userPictureDialog->FileName);
        }
        catch (...)
        {
          ShowMessage("There was an error while opening the file.");
        }
      }
    }