Input Data to Display Newlines in ASP.NET

February 14th, 2009
By: Cory Mathews

In asp.net input taken from a plain text box will not display newline characters (Hitting the enter key) when outputting to the browser.

So for example you have a text box that users can input text into, they put a couple paragraphs in it and submit that data to the database. If you just strait output the content to the browser you will see one giant blob of text. So how can you fix this?

By converting the newline to a html
tag we can fix the problem. So with a little c# function we have the trick done.

public String FixLabelOutput(String val) {
    return val.Replace(Environment.NewLine, "<br />");
}

As you see our function simple returns all newlines as <br /> which will fix the way it is outputted.

In the aspx page you need to have this to display the corrected text. This of course can be placed in a label or just strait printed.

<%# FormatHtml(Eval("TextInfo").ToString()) %>