Firemonkey: Setting TLabel Text causes String Index out of Range Exception

强颜欢笑 提交于 2019-12-13 20:30:55

问题


I have a method which builds a help message and then sets a TLabel's text property to that help message. However, whenever I attempt to set the text of the label, I get the following exception:

'String index out of range. (-1) Must be >=0 and <=42'

The method is as follows:

void __fastcall TPasswordChangeForm::BuildHelpMessage()
{
    String HelpMsg = "";

    if( NewPassEdit->Text.Length() < MinPasswordLength )
    {
        HelpMsg += "Password length too short.";
    }
    else
    {
        HelpMsg += "Password length OK.";
    }

    HelpMsg += "\n";

    if( NewPassEdit->Text == ConfirmPassEdit->Text )
    {
        HelpMsg += "Passwords match.";
    }
    else
    {
        HelpMsg += "Passwords do not match.";
    }

    ShowMessage( HelpMsg ); //added for debugging, shows string as expected

    HelpLabel->Text = HelpMsg;  //exception thrown here
}

I added a ShowMessage call just to check the value of my string. It shows up just fine. I am also able to set the label to be any arbitrary value such as:

HelpLabel->Text = "This message works!";

Am I doing something wrong as I build the HelpMsg String?

Edit: Commenting out the line which adds the \n to the String fixes the problem. Similarly, the following code will cuase the exception:

String test = "this is a test";
test += "\n";
test += "test 2";

HelpLabel->Text = test;

What is it about the \n that causes issues? How do I correctly add a new line?


回答1:


Currently updating to new new C++ Builder so cant play around with your snippet. I have method's for handling error messages which are output to a log tab as opposed to the ShowMessage, rather than using a string though I use a TStringList. For example:

void __fastcall TPasswordChangeForm::BuildHelpMessage()
{
    TStringList HelpMsg = new TStringList(this);

    if( NewPassEdit->Text.Length() < MinPasswordLength )
    {
        HelpMsg->Add("Password length too short.");
    }
    else
    {
        HelpMsg->Add("Password length OK.");
    }

    if( NewPassEdit->Text == ConfirmPassEdit->Text )
    {
        HelpMsg->Add("Passwords match.");
    }
    else
    {
        HelpMsg->Add("Passwords do not match."_;
    }

    ShowMessage(HelpMsg->Text); //added for debugging, shows string as expected

    HelpLabel->Text = HelpMsg->Text;  //exception thrown here
}

By using TStringList or TStrings (parent) when you access the Text property the strings within the object are output, each separated by a carriage return and line feed.

See the TStringList Docs here - hope this is of some help!



来源:https://stackoverflow.com/questions/32319253/firemonkey-setting-tlabel-text-causes-string-index-out-of-range-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!