Return a line break or carriage return in ASP.NET page

ASP.NET, C#, VB.NET 3.4.2009 1 Comment

I came across the issue today of needing to output some text from a multiline textbox and having a few issues on preserving the line breaks/carriage returns from the textbox. If you view the source on the page, it would look correct, but yet the display on the HTML page would show no line breaks.

Assuming my textbox looks like this


hi
this
is
my
test

The output would look like this

hi this is my test

This is because the browser is interpreting the markup and since there is only breaks but no HTML, browers just default all that white space to a single space. What you need is to send a < BR > tag to the browser for every line break. You use the Replace method to replace all newline code with the < BR > tag.

C#
Response.Write(txt.Text.Replace(Environment.NewLine, "<BR>"));

VB.NET
Response.Write(txt.Text.Replace(Environment.NewLine, "<BR>"))

One Response to "Return a line break or carriage return in ASP.NET page"

  1. Truly it is very interesting for me to read that post. Thanx for it. I like such themes and anything connected to this matter. I definitely want to read a bit more on that blog soon.

Leave a Reply