Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep line breaks in SQL Server using ASP.NET and C#?

I have a multiline text box. User will give brief details in that text box.

Like this:

user entering data in multiline textbox

After I saved this in SQL Server and retrieve it again, it is showing like the following screenshot:

without line break

What can I do to keep the line breaks? Do I need to encrypt something before I save the data in SQL Server?

Thanks.

This is my code:

<div id="Description_id" runat="server">
</div>

C# code:

string description = rd["job_description"].ToString();
Description_id.InnerText = description.Replace("\r\n", "<br/>");
like image 695
Faisal Avatar asked Nov 01 '25 17:11

Faisal


1 Answers

When you get the text contents form a <textarea> or <input> the line breaks are stored as newline characters - basically \n for Unix based systems and \r\n for Windows.

You will need to convert these newline characters to <br /> tags, so that they are displayed properly in input and the line breaks are preserved. As an example, you could do something like this:

var outputHtml = textFromDb.Replace( "\r\n", "<br />" ).Replace( "\n", "<br />" );

This will ensure that the replace will be applied for both Unix and Windows newlines. Windows format replace comes first, because the Unix format is its substring.

Alternatively, you can also wrap the text from the database into a <pre>, which will preserve the whitespace characters (including newlines).

like image 153
Martin Zikmund Avatar answered Nov 03 '25 08:11

Martin Zikmund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!