Wednesday, September 17, 2008

Show line breakes in Asp.net Label

To show line breaks in a server side asp.net label, you can either use a HTML formatted text or a plain text.

HTML formatted text contains “
” tags so while rendering the control .net framework handles the task to show the proper html formatted text into a Label.

Example:
lblDescription.Text=”name
description”;
The above code will display a line gap between name and description.
But in case if user inputted data using a non-HTML enabled TextBox then it is a point of problem.

While displaying data, inputted by simple multiline TextBox, line breaks looses its state and when the data displayed on a label it looks like a simple constant text line. Interestingly if you try to show the same data back in a TextBox it will look nice with proper line breaks. But we can’t use TextBox every where because of designing requirements.

To keep the line breaks you must convert the HTML new line special indicator to HTML break “
” tag.

Solution:
lblDescription.Text = txtInput.Text.ToString().Replace(Environment.NewLine, “<br>”);

The above code replaces the “NewLine” indications to “<br>” at run time, and displays the data same as input formatting.

Download Source Code

2 comments:

Rem said...

Nice post...

Fuady said...

Thank you so much!
This is what I need since my first time learning ASP.NET..

I even didn't know that there is System.Environment namespace before.. what a shame..

Once again, thanks!