bowerdotjson
bowerdotjson

Reputation: 31

How do I store multiline text in a database?

Here is my code:

public static String ReplaceNewLines(String source, bool allowNewLines)
{
     if (allowNewLines)
          source = source.Replace("\r\n", "<br />");
     else
          source = source.Replace("\r\n", " ");
     return source;
}

protected void btnSubmit_onClick(object sender, EventArgs e)
{
     String txtInput = ReplaceNewLines(txtQuestion.Text, true);
     String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

     using (SqlConnection conn = new SqlConnection(connectionString))
     {
          // Sql Commands here...
     } 
}

When the button above is clicked, data is inserted into the database like this:

Test line one. <br /> test line two.

What I want is it to look like this:

Test line one.<br />Test line two.

How do I set up my code behind so the <br /> does not show up in the SQL query and creates another line in my page when I call it from the database?

Upvotes: 3

Views: 3139

Answers (3)

Brian Pressler
Brian Pressler

Reputation: 6713

You can try:

source = source.Replace("\r\n", "" + ((char)13).ToString() + (char)10).ToString();

Those are the carriage return and line feed characters.

Upvotes: 1

Charles Farr
Charles Farr

Reputation: 379

Add "carriage return" and "line feed" characters, see the example

SELECT 'THIS IS A COMMENT LINE 1' + CHAR(13) + CHAR(10) + 'THIS IS LINE 2'

Output

THIS IS A COMMENT LINE 1 THIS IS LINE 2

Upvotes: 0

Juan
Juan

Reputation: 1382

You are storing the correct information. The break (<br/>) will give you a new line if you show the result in a browser for example who can make an interpretation of the hmtl.

Upvotes: 0

Related Questions