dotnetnoob
dotnetnoob

Reputation: 11330

Stringbuilder text not displaying on new lines

I have a generic html control - a 'P' tag, which i've added a runat="server" to.

I construct a string using Stringbuilder methods and apply this to the InnerHtml attribute of the tag.

The text,which contains a number of sb.Appendline()'s still displays as a paragraph would, wrapping but without creating any new lines. However, When i look at the markup created, the new lines are there, shown as spacing.

This is also the case with a DIV

Anyone got any ideas as to how i fix this?

Code below:

        var sb = new StringBuilder();
        sb.Append("Congratulations!");
        sb.AppendLine();
        sb.AppendLine();
        sb.AppendFormat("Your application was accepted by <b>{0}</b>.", response.AcceptedLender);
        sb.AppendLine();
        sb.AppendFormat("Your reference number is <b>{0}</b>.", response.PPDReference);
        sb.AppendLine();
        sb.AppendLine();
        sb.Append("Click the button below to sign your loan agreement electronically and collect your cash.");

        AcceptedMessage.InnerHtml = sb.ToString();

Upvotes: 2

Views: 7388

Answers (4)

CoperNick
CoperNick

Reputation: 2533

string messagePattern = @"
<p>Congratulations!</p>
<p>Your application was accepted by <b>{0}</b>.<br />
   Your reference number is <b>{1}</b>.</p>
<p>Click the button below to sign your loan agreement 
   electronically and collect your cash.</p>";

AcceptedMessage.InnerHtml = string.Format(
    messagePattern, 
    response.AcceptedLender, 
    response.PPDReference);

Upvotes: 0

codingbiz
codingbiz

Reputation: 26386

The lines appended by StringBuilder does not show in the browser. Browser only recognises
and new line. So you have to include the tag for displaying in browsers

  sb.AppendLine("some text here <br />");

The new lines will show in console applications and not browsers

You can as well replace the new lines

AcceptedMessage.InnerHtml = sb.ToString().Replace("\n", "<br />");

Upvotes: 0

gkakas
gkakas

Reputation: 377

You have to convert the stringlbuilder newlines (\n) into BR tags

so that they can be rendered in HTML newlines.

Even better IMO is to enclose the whole lines in P tags

Upvotes: 2

Joel Etherton
Joel Etherton

Reputation: 37533

Instead of using AppendLine should use AppendFormat:

myStringBuilder.AppendFormat("{0}<br />", strToAppend);

If you need these line breaks to remain "as is" because you're displaying it in a text file or something of that nature, you'll need to replace the new line text with html breaks when you're calling the .ToString() method.

myStringBuilder.Replace(Environment.NewLine, "<br />").ToString();

Using Environment.NewLine here may not work, you may actually need to replace \r\n.

Upvotes: 11

Related Questions