How to break a line on a web page?

I want to format the content before showing it on a web page. I store '\ r \ n \' as enter into the database and try to replace it before showing the content on the web page. server side my code is:

lblComments.Text = Server.HtmlEncode(((DataRowView)e.Item.DataItem).Row["Comment"].ToString().Replace("\r\n", "<br>")); 

I am using Server.HtmlEncode .

My output should be:

 Comment Type: Public Comment: Commented on the Data by user A 

But, it shows me everything on one line.

+4
source share
3 answers

You need to use

 .Replace("\r\n", "<br/>") 

And only AFTER Server.HtmlEncode, because you don’t want <br/> to get the encoding itself before &lt;br/&gt; (raw), displaying as <br/> literally.

+2
source

You can wrap the output in a <pre>...</pre> element instead of replacing line breaks with <br> . Therefore, line breaks should be kept.

eg. place the <pre> element around your label:

 <pre><asp:Label id="lblComments" runat="server" /></pre> 
0
source

Try

 Replace("\n", "<br>") 

This test worked without coding

 string comments = @"Comment Type: Public Comment: Commented on the Data by user A"; lblComments.Text = comments.Replace("\n","<br>"); 
0
source

Source: https://habr.com/ru/post/1438600/


All Articles