1

I have winforms that contains pictureBox form, I want to retrieve an img from DB to that control using LINQ.

This is the error when compiling,

CS1061: IQueryable does not contain a definition for Image and no extension method Image accepting a first argument of type IQueryable could be found (are you missing a using directive or an assembly reference?)

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        // Get as single image from the database
        var q = from image in context.Products
                where image.Pro_ID == 1
                select image;
        // Convert the byte[] to an System.Drawing.Image
        img.Image = ByteArrayToImage(q.Image.ToArray());
    }

    private byte[] ImageToByteArray(System.Drawing.Image imageIn)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
    }

1 Answer 1

1

Your problem is ImageToByteArray accepts an image as varieble but you used this:

ByteArrayToImage(q.Image.ToArray());

That use this function with an array as varieble.

After getting q from sql (If q is a byte array)

var q = (from x in context.Products
               where x.Pro_ID == 1
               select x.Image).FirstOrDefault();


Image image1 = byteArrayToImage((byte[])q);

and a method

public Image byteArrayToImage(byte[] byteArrayIn)
{
     using (var ms = new MemoryStream(byteArrayIn))
     {
        return Image.FromStream(ms);
     }
}

Do not forget using the name space System.Drawing.Image

9
  • What you mean remove it? you must edit that. and what is the error? what is the img ? Commented Feb 26, 2017 at 12:56
  • I thought you meant I should remove the array. How can I edit it? in the parameter, q.Image.ToArray(), the red line is under image.
    – Emi
    Commented Feb 26, 2017 at 13:02
  • thank you for your effort, but i faced the problem. "Can not convert type 'System.linq.IQuerable<.....Product> to 'byte[]' ".
    – Emi
    Commented Feb 26, 2017 at 13:35
  • What is the column name that the byte array saved in? Commented Feb 26, 2017 at 13:36
  • 2
    The data type muse be VARBINARY(MAX) . I do not think nvarchar(max) works. Create another data base with change i said and i will give you the code to get array from sql. Commented Feb 26, 2017 at 13:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.