user3229034
user3229034

Reputation: 67

Not able to remove the apostrophe

This piece of code works properly if there is any value without the apostrophe. But if the ddList.SelectedValue is, say, Women's day, it shows "Incorrect syntax near 's'. Unclosed quotation mark after the character string ''." I tried the albumName.Replace but no luck so far.

protected void btnUpload_Click(object sender, EventArgs e)
{
    string albumName = ddList.SelectedValue.ToString();
    albumName.Replace("'", "''");

    conn.Open();
    SqlCommand command = new SqlCommand("select ID from Album where AlbumName = '" + albumName + "'", conn);

    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        AlbmID = Int32.Parse((reader["ID"].ToString())); 

    }
    reader.Close();

    if (fileuploadimages.HasFile == false)
    { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('No File Uploaded.')</script>", false); }
    else
    {
        //Get Filename from fileupload control
        string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
        //Save images into SlideImages folder
        fileuploadimages.SaveAs(Server.MapPath("Pictures/" + filename));
        //Open the database connection

        //Query to insert images name and Description into database
        SqlCommand cmd = new SqlCommand("Insert into Images(ImagePath,Album_ID,ImageDesc) values(@ImagePath,@Album_ID,@ImageDesc)", conn);
        //Passing parameters to query
        cmd.Parameters.AddWithValue("@ImagePath", filename);
        cmd.Parameters.AddWithValue("@Album_ID", AlbmID);
        cmd.Parameters.AddWithValue("@ImageDesc", txtDescription.Text);
        cmd.ExecuteNonQuery();
        //Close dbconnection
        conn.Close();
        txtDescription.Text = "";
        BindDataList();
    }
}

Upvotes: 3

Views: 679

Answers (2)

Joe
Joe

Reputation: 1669

.Replace("'",@"\'") 

This will escape your single quote/apostrophe

Upvotes: 1

Clever Neologism
Clever Neologism

Reputation: 1332

SqlCommand command = new SqlCommand("select ID from Album where AlbumName = @name", conn);
command.Parameters.Add(new SqlParameter("@name", albumName));
.
.
.

In addition, you should wrap the connection,command, and reader objects in a using() {} construct to dispose of the resources in a timely fashion.

Use parameters like this whenever dynamic things are being put into a SQL string to avoid errors like this, as well as SQL injection attacks and other vulnerabilities.

In addition, you can rapidly replace parameters for executing multiple queries without having the rebuild the string.

Upvotes: 4

Related Questions