Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep line breaks while saving to SQL database and retrieving it to show inside a label

Tags:

c#

css

asp.net

I have a textarea where I enter some text in multiple lines by pressing enter:

<asp:TextBox ID="tbMessage" runat="server" ClientIDMode="Static" 
     TextMode="MultiLine" Columns="30" Rows="5"></asp:TextBox>

I save the text from code-behind (MessageText column is of type varchar):

using (SqlCommand qSave = new SqlCommand())
{
    qSave.Connection = oCon;
    qSave.CommandType = CommandType.Text;
    qSave.CommandText = @"INSERT INTO [Db1].[dbo].[Table1] (MessageText) VALUES (@MessageText)";
    qSave.Parameters.AddWithValue("@MessageText", tbMessage.Text);

    try
    {
        oCon.Open();
        qSave.ExecuteNonQuery();
    }
    catch (SqlException ce)
    {
    }
    finally
    {
        oCon.Close();
    }
}

I retrieve the column and show it inside a label from code-behind:

public void MyFunction()
{
    strSql = @"SELECT * FROM [Db1].[dbo].[Table1]";

    using (SqlConnection conn = new SqlConnection(gloString))
    {
        try
        {
            // create data adapter
            SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
            // this will query your database and return the result to your datatable

            myDataSet = new DataSet();
            da.Fill(myDataSet);

            string specific = "";
            string generic = "";
            string strTemp = "";

            foreach (DataRow r in myDataSet.Tables[0].Rows)
            {
                if (r["MessageText"].ToString().Length <= 65)
                {
                    strTemp = r["MessageText"].ToString();
                }
                else
                {
                    strTemp = TruncateLongString(r["MessageText"].ToString(), 65) + "...";
                }

                specific += "<span class='hoverText tooltip' title='" + this.Server.HtmlEncode(r["MessageText"].ToString().Replace("\r\n", "<br />")) + "'>" + this.Server.HtmlEncode(strTemp) + "</span><span class='dvMsgInitHidden'>" + this.Server.HtmlEncode(r["MessageText"].ToString().Replace("\r\n", "<br />")) + "</span><br /><br />";
            }

            lblMessage.Text = specific;

            upMessage.Update();
        }
        catch (Exception ce)
        {
        }
    }
}

public string TruncateLongString(string str, int maxLength)
{
    return str.Substring(0, maxLength);
}

As you can see from the following screenshot the title shows correctly but the message is all jumbled into one line:

enter image description here

Please help me resolve it.

like image 742
SearchForKnowledge Avatar asked Dec 20 '22 06:12

SearchForKnowledge


1 Answers

The following CSS takes care of it:

white-space: pre-wrap;
like image 163
SearchForKnowledge Avatar answered Jan 11 '23 23:01

SearchForKnowledge