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?
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!