SearchForKnowledge
SearchForKnowledge

Reputation: 3751

How to escape apostrophe when displaying inside a ASP.NET label

I have the following function which truncates a SQL Server varchar column and adds it to a string:

public void Pp()
{
    strSql = @""; //query
    using (SqlConnection conn = new SqlConnection(gstr))
    {
        try
        {
            SqlDataAdapter da = new SqlDataAdapter(strSql, conn);

            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 += "</b><span class='hoverText' title='" + r["MessageText"] + "'>" + strTemp + "...</span>";
                strTemp = "";
            }

            lblMessage.Text = "<b>SPECIFIC MESSAGES:</b> <br />" + specific;
        }
        catch (Exception ce)
        {
        }
    }
}
public string TruncateLongString(string str, int maxLength)
{
    return str.Substring(0, maxLength);
}

If the r["MessageText"] contains an appostrophe, it cuts off anything after it. (full text: no way no way HERE we go again but this is not working. Is it? or Is it not? I can't be too sure though. Can someone please check.)

Here is an example of a live preview (the title is shown but gets cut off because of the apostrophe):

enter image description here

Here is the source (the apostrophe is shown in the purple box. Also the color coding gets out of whack due to the apostrophe, which means the code is not correct):

enter image description here

How can I ensure it doesn't escape any escape characters, e.g. ', /, \.

Upvotes: 0

Views: 2245

Answers (2)

scubasteve623
scubasteve623

Reputation: 647

.Replace(" ' ", "\\' "); You will probably want to do the same with double quote as well.

Upvotes: 1

Dai
Dai

Reputation: 155270

You need to encode the HTML first.

Call this.Server.HtmlEncode( str ). This will also protect against other special characters like & and <.

That said, you're using single-quotes for attribute delimiters but HtmlEncode only encodes double-quotes, so you need to change your code to this:

specific = String.Format( CultureInfo.InvariantCulture, @"</b><span class=""hoverText"" title=""" + this.Server.HtmlEncode( r["MessageText"] ) + """>" + strTemp + @"...</span>";

Upvotes: 4

Related Questions