Search code examples
delphidelphi-xe8

Why does the E2362 Cannot access protected symbol TControl.Text appear?


Here is the code that causes the error:

procedure TfrmQuoteTemp.showData;
 begin
  lblFirstName.Text := query.FieldByName('First Name').AsString;
  lblLastName.Text := query.FieldByName('Last Name').AsString;
  lblAddress.Text := query.FieldByName('Address').AsString;
  lblTown.Text := query.FieldByName('Town').AsString;
  lblCounty.Text := query.FieldByName('County').AsString;
  lblPostcode.Text := query.FieldByName('Postcode').AsString;
  lblTelNo.Text := query.FieldByName('TelNo').AsString;
 end;

This error happens only with Tlabel and I cannot change their Text property at all.


Solution

  • If you're writing a VCL-based application, the error message is quite clear - Text is protected (not published) in TLabel, which publishes the Caption property instead. Change your code to use that property.

    lblFirstName.Caption := query.FieldByName('First Name').AsString;
    

    For future reference, this can be seen both in the Object Inspector (which shows that the TLabel has a published Caption property and not a Text property) and by using Code Insight in the IDE (type lblFirstName. and hit Ctrl+Space), which does not offer the Text property but shows the Caption property if you scroll through the choices.

    (Also, as a general rule of thumb (at least in the VCL): if the control accepts user input (the user can type into it) like TEdit and TMemo, it publishes a Text property; if not (TLabel or TButton, for instance), it publishes Caption property instead. As TLabel does not accept user input, it publishes Caption and not Text.)