Search code examples
c#stringbuildersplistitem

How can I add a blank line to my StringBuilder?


It is a known "issue" that doing this:

sb.AppendLine();

...will not add a blank line, as one would expect (as discussed here, for instance).

However, it is commonly believed that this will work:

sb.AppendLine(Environment.NewLine);

...but it's not working for me. I've got this code:

for (int i = 0; i < listOfListItems.Count; i++)
{
    sb.AppendLine(Environment.NewLine);
    lc = listOfListItems[i];
    sb.AppendLine(String.Format(@"<p>Request date is {0}; Payee Name is {1}; Remit Address or Mail Stop is {2}; Last 4 of SSN or ITIN is {3}; 204 Submitted or on file is {4}; Requester Name is {5}; Dept or Div Name is {6}; Phone is {7}; Email is {8}</p>",
        lc.li_requestDate, lc.li_payeeName, lc.li_remitAddressOrMailStop, lc.li_last4SSNDigitsOrITIN, lc.li_204SubmittedOrOnFile, lc.li_requesterName, lc.li_deptDivName, lc.li_phone, lc.li_email));
}

All the data is being added to the StringBuilder, and then to the form that gets generated, but there are no spaces between the list items - the "sb.AppendLine(Environment.NewLine)" is appending nothing.

What must I do to force a line between the individual list item outputs?


Solution

  • The StringBuilder.AppendLine does add a \r\n to the end of the string. You do not need to explicitly add another statement like StringBuilder.AppendLine(System.Environment.NewLine). You can cross check this by converting your string returned from a StringBuilder to an Array of chars, where you can see the newlines.

    In your example, it looks like you are trying to display the output in HTML (looking at the p tag in your string) and the newline is not visible in your HTML. In order to achieve this, you may want to add a br to your string.

    sb.AppendLine("<br/>");
    

    A carriage return (\r\n) has no meaning within HTML tags.