How to retain carriage returns or line breaks in an ASP.NET web page
The solution is fairly obvious once the newcomer realises that a web page is only the browser's interpretation of html markup, and that a new line in html is represented by the <br /> tag. So what is needed is a way to swap carriage returns or line feeds with the <br /> tag. Well, a way to Replace() them, actually.
<%# Eval("MyMultiLineValue").ToString().Replace(<linebreak>,"<br />") %>
The string.Replace() method allows this, but we also need to identify what we want to replace with the html tag. How is a new line <linebreak> represented in C# or VB.Net?
In C#, it's "\r\n", while in VB.Net, it's vbcrlf. However, there is also a language independent option that does just the same thing: Environment.NewLine.
<%# Eval("MyMultiLineValue").ToString().Replace(Environment.NewLine,"<br />") %>
Currently rated 4.57 by 7 people
Rate Now!
Date Posted:
06 April 2007 19:55
Last Updated:
30 May 2007 10:13
Posted by:
Mikesdotnetting
Total Views to date:
7671
Printer Friendly Version
Comments
30 March 2009 01:06 from David
Thank you very much.
18 April 2009 15:57 from Rajashree
It's fantastic.
Thanks you.
19 June 2009 18:00 from andy
THANKS!
10 July 2009 23:42 from Suranga
Thank you. It works :)
24 July 2009 11:13 from Michael
Thanks a million! I've been using plugin's like tinymce or a customize TextArea just to replace the line breaks in a TextArea. I didn't know or ask enough about Environment.NewLine...great!
03 September 2009 15:01 from foo
I keep getting the following error:
Microsoft VBScript compilation error '800a0414'
Cannot use parentheses when calling a Sub
/admin.asp, line 39
Eval(content).ToString().Replace(Environment.NewLine,"
")
04 September 2009 06:30 from Mikesdotnetting
@foo You get that error because you are not using ASP.NET. You are using classic ASP. They are totally different.
01 October 2009 14:16 from newbieweb
hey mike, actually i'm new to web and id like to know where can i exactly put your suggested code? i'm using detailsview and i wanted the data from sql to appear with linebreaks.. is it in a code behind or within the asp control? im using 3.5 by the way.. thanks in advance!
02 October 2009 11:19 from Mikesdotnetting
@newbieweb
You would put it in the aspx page as part of the control markup eg:
<asp:Label runat="server" ID="MyLabel" Text='<%# Eval("MyMultiLineValue").ToString().Replace(<linebreak>,"<br />") %>' />
21 November 2009 12:57 from Manishdhaduk
Thank you very very very much
27 January 2010 22:00 from parabellum
Ingenious solution. Thank you for sharing.
05 February 2010 19:17 from reader
Perfect. Thanks.


08 January 2009 00:36 from Jack
Thanks for this article! it helped me a lot. I think i'll start coming here a lot earlier during my problem solving from now on.