Reputation: 411
I creating asp.net c# web application. I have a linkButton (lnkDelete) on first column of each row of gridview. Also i am adding an attribute dynamically to that link button inside "RowDataBound" event of GridView. Like as follows :
lnkDelete.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete this Product :" +
DataBinder.Eval(e.Row.DataItem, "ProductName") + "')");
Now What i am trying to do is when user click that link button a javascript confirm popup open up ,asking "Are you sure you want to delete this product". Every thing work fine . But Problem occures when the name of the products comes with sngle quote. Like : Product'One. Syntax Error comes in ErrorConsole (javascript) when i click lnkDelete and error is : ( illegal character ) I know the problem is with single quote.
Please suggest me what change required in my above code. I hope i am clear.
Upvotes: 2
Views: 3725
Reputation: 1260
I did the similar thing in one of my automated tools for Search project. Here is what you can try:
protected void grdKeywords_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton linkDeleteButton = e.Row.FindControl("lnkdel") as LinkButton;
Label lblGridKeyword = e.Row.FindControl("lblGridKeyword") as Label;
TextBox txtGridBox = e.Row.FindControl("txtGridKeyword") as TextBox;
if (lblGridKeyword != null)
{
if (lblGridKeyword.Text.Contains("'"))
{
lblGridKeyword.Text = lblGridKeyword.Text.Replace("'", "'");
}
}
if (txtGridBox != null)
{
if (txtGridBox.Text.Contains("'"))
{
txtGridBox.Text = txtGridBox.Text.Replace("'", "`");
}
}
if (txtGridBox == null)
linkDeleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure about deleting keyword: " + lblGridKeyword.Text + " ?')");
else if (lblGridKeyword == null)
linkDeleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure about deleting keyword: " + txtGridBox.Text + " ?')");
}
}
lblGridKeyword is the label which holds the data that contains the single quote. I replaced that using ' at the time of RowDataBound. This worked for me.
Upvotes: 0
Reputation: 457
Do you tried escaping the string?
If you have a escaped string, you can unescaping with javascript.
lnkDelete.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete this Product :' + unescape(\'" + escapedString + "\'))");
Upvotes: 0
Reputation: 2099
Instead of DataBinder.Eval(e.Row.DataItem, "ProductName")
You can use
HttpUtility.HtmlEncode(DataBinder.Eval(e.Row.DataItem, "ProductName").ToString())
Upvotes: 0
Reputation: 263683
How about adding \
in the single quote?
DataBinder.Eval(e.Row.DataItem, "ProductName").ToString.Replace("'", "\\'")
Upvotes: 6