0

I am using SqlReader object(reader) to assign a string value from Sql-server database to an image's ImageUrl, but the ImageUrl is always empty while the reader object doesn't satisfy the while loop condition when debugging.

protected void Button3_Click(object sender, EventArgs e)
    {
        string query = "select profilePicture from Users where username = '@username'";
        command = new SqlCommand(query, connection);
        command.Connection = connection;
        command.Parameters.Add("@username", SqlDbType.VarChar).Value = User.Identity.Name;
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                ProfilePhotoButton.ImageUrl = reader[0].ToString();
            }
        }
        connection.Close();
    }

1 Answer 1

3

You have single quotes enclosing your parameter. Remove that.

 string query = "select profilePicture from Users where username = '@username'";
                                                                  //HERE

It should be:

 string query = "select profilePicture from Users where username = @username";

Enclosing value in single quotes would be take care by the parameter type you have specified while adding parameters to your command.

As a side note, enclose your Command and Connection object in using statement as well to ensure disposal of resources.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.