RubbleFord
RubbleFord

Reputation: 7646

Best way to preserve Line Breaks in ASP.NET

I have some text coming in from a textarea and want to preserve the line breaks etc. So when I put the content back on the screen it looks correct!

What's the best way to do this in asp.net.

Upvotes: 1

Views: 5556

Answers (3)

backslash17
backslash17

Reputation: 5390

The problem with textarea component is that it works in plain text with no HTML tags included, so you need to replace each line feed with a "br" and each additional whitespace with the white space HTML entity. Is just matter of replacement.

mytextarea.text.replace("\n","<br/>");
mytextarea.text.replace("text character to be replaced","replacing HTML entity");

You can use two consecutive white spaces inside the quotes to be replaced with &nbsp ,this is just for replacing spaces with more than two consecutives whitespaces chars in order to make the resulting HTML code more readable. You can adjust this at your requirements.

Upvotes: 2

Brian Boatright
Brian Boatright

Reputation: 36774

@RubbleFord I don't have the points just yet to edit your question but I think you should change the title to "Best Way to Preserve Line Breaks" so it will better match your question and the answers provided.

To preservce whitespace or force it in HTML use "&nbsp;"

Upvotes: 0

Ahmad Mageed
Ahmad Mageed

Reputation: 96557

When you read your data back to the screen replace the line breaks with "<br />" tags:

txtArea.Text = input.Replace(Environment.NewLine, "<br />");

Upvotes: 9

Related Questions