0

I'm hoping someone has the answer to this problem. I am trying to pass a code behind value (@Artist) to the SqlDataSource control in an aspx file so that the value has a '&' in the string. The code works if there is no & in the value. I've tried escaping the character but get an empty string returned. If I remove the '&' code, it works just fine on values that do not have it.

Here's the code behind:

public partial class Artist : System.Web.UI.Page
{
    public string _Artist;

    protected void Page_Load(object sender, EventArgs e)
    {
        string _Artist = Request.QueryString.ToString();  
        _Artist = Artist
            .Substring(7, _Artist.Length - 7)
            .Replace("+", " ")
            .Replace("&", "\\&"); 
        SqlDataSourceAlbums.SelectParameters.Add("Artist", _Artist);
    }
}

Here's the asp:SqlDataSource SELECT query:

SELECT DISTINCT Album FROM dbo.c_mymusic_albums WHERE (Artist = @Artist)

The result is an empty string. How do I fix it so the SELECT query returns value(s)? I'm using C#.

Thanks!

Hayden
  • 2,902
  • 2
  • 15
  • 29
sflatbush
  • 1
  • 2
  • What is artist value? – AliK Jul 14 '21 at 21:57
  • The artist value where there is no result to the query is "Big Brother & The Holding Company". – sflatbush Jul 14 '21 at 22:00
  • https://stackoverflow.com/questions/12961215/escaping-ampersand-character-in-sql-string – Andy Stagg Jul 14 '21 at 22:03
  • Replace with \& – AliK Jul 14 '21 at 22:03
  • @Andy Stagg, to clarify, this problem is different. When using the returned value as a url parameter, it passes this: ?Artist=Big+Brother+%26+The+Holding+Company. Can %26 be replaced by & in the asp.net code so that the SELECT statement has the correct query? – sflatbush Jul 14 '21 at 22:14
  • @Alik, replacing \\& with \& causes an error. Error CS1009 Unrecognized escape sequence – sflatbush Jul 14 '21 at 22:16
  • What about using the char value of & not sure what it is off the top of my head but char(xx) would replace &. – AliK Jul 14 '21 at 22:36

1 Answers1

0

I figured out the problem. Replacing %26 with & without escape characters fixed it. Sorry I left out the part where using the url parameter. It didn't cross my mind. The escaping of & wasn't necessary because & gets passed properly when using it to replace %26. Thanks for your help!

sflatbush
  • 1
  • 2