tags:

views:

395

answers:

3

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.

+2  A: 

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.

backslash17
+5  A: 

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

txtArea.Text = input.Replace(Environment.NewLine, "<br />");
Ahmad Mageed
Just a hint, I suspect that your `<br />` tag was invoked, rather than presented. To stop this happening you should enclose any html tags with back-ticks (`) to indicate that it's code, not html.
David Thomas
That's what I had pretty much thought it was a little noddy cheers, for the confirmation though.
RubbleFord
@drthomas: Thanks. Fixed it after I saw that!
Ahmad Mageed
A: 

@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;"

Brian Boatright