Question

I'm trying to retrieve an image stored as a varbinary(max) column from my SQL Server 2008 database. When the image column is not equal to NULL then I get the image from the database. Below is the code I use to retrieve my image. Do help me take a look on my code, I not sure where I did wrongly. Thanks!

protected void Page_Load(object sender, EventArgs e)
{
    string strQuery = "select profilepicture from MemberAccount where nric='"+ Session["nric"] +"' and profilepicture IS NOT NULL";
    SqlCommand cmd = new SqlCommand(strQuery);
    DataTable dt = GetData(cmd);
    if (dt != null)
    {
       download(dt);
    }
}

private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;

    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }
    catch
    {
        return null;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}

private void download(DataTable dt)
{
    Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "image/jpg";
    Response.BinaryWrite(bytes);
    Response.End();
}

Line:

Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];

Error:

There is no row at position 0.

Was it helpful?

Solution

Defensive database programming 101: you need to check whether you get data or not! You cannot convert nothing to an image... and you cannot just blindly assume you'll get data. ALWAYS check!

private void download(DataTable dt)
{
    // check if you have any rows at all 
    // no rows -> no data to convert!
    if(dt.Rows.Count <= 0)
       return;

    // check if your row #0 even contains data -> if not, you can't do anything!
    if(data.Rows[0].IsNull("profilepicture"))
       return;

    Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "image/jpg";
    Response.BinaryWrite(bytes);
    Response.End();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top