Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display label text with line breaks in c#

Tags:

c#

asp.net

Is it possible to display the label text with line breaks exactly as per the image

enter image description here

I need the text on the label to be printed exactly can some one help me, my desired text that has to be shown on the label will be stored in a string-builder

like image 435
Developer Avatar asked Dec 14 '12 12:12

Developer


People also ask

How do you display a label with text with line breaks?

You can wrap your asp label in a pre tag, and it will display with whatever line breaks are set from the code behind. Show activity on this post. You can also use <br/> where you want to break the text.

How do you add a line break in Uilabel?

To add line breaks in the text we'll use \n character in the string we want to assign to the label.

How do you break a line in a label in HTML?

Basic HTML Line Break Syntax You can insert line breaks in HTML with the <br> tag, which is equivalent to a carriage return on a keyboard.

How do you break a line in ASPX CS?

Line breaks in HTML or ASP.NET is represented by the < br /> tag. In some cases, you will need to convert an existing string that contains new lines to a valid HTML code that includes < br /> tags.


2 Answers

You may append HTML <br /> in between your lines. Something like:

MyLabel.Text = "SomeText asdfa asd fas df asdf" + "<br />" + "Some more text"; 

With StringBuilder you can try:

StringBuilder sb = new StringBuilder(); sb.AppendLine("Some text with line one"); sb.AppendLine("Some mpre text with line two"); MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />"); 
like image 90
Habib Avatar answered Sep 18 '22 12:09

Habib


I know this thread is old, but...

If you're using html encoding (like AntiXSS), the previous answers will not work. The break tags will be rendered as text, rather than applying a carriage return. You can wrap your asp label in a pre tag, and it will display with whatever line breaks are set from the code behind.

Example:

<pre style="width:600px;white-space:pre-wrap;"><asp:Label ID="lblMessage" Runat="server" visible ="true"/></pre> 
like image 36
Adam Scharp Avatar answered Sep 20 '22 12:09

Adam Scharp