SqlReader object does not read

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();
    }

Upvotes: 0

Views: 35

Answers (1)

Habib
Habib

Reputation: 223227

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.

Upvotes: 3

Related Questions