Sql – How to retrieve an Image from MS SQL Server to bind in Gridview ASP.NET by using LINQ to SQL

asp.netimagelinq-to-sqlsql server

I have a binary file which stores in the customerPicture column that has Image as a datatype in the CUSTOMERs table.

I have saved an image by using this line of code in LINQ to SQL.

Dim db = new MyCompanyDataContext
Dim newCus = new CUSTOMERs
Dim filebyte As Byte() = fileUploader.FileBytes
Dim fileBinary As New System.Data.Linq.Binary(filebyte)
newCus.customerPicture = fileBinary

Then now I want to retrieve this binary file to bind in the gridview in ASP.NET by using LINQ to SQL, but I don't know how. Can you please show me some ways to reach the solution?

Best Answer

you can use Httphandler to retrive the images from the database.

            <ItemTemplate>
                <asp:Image ID="imgPhoto" runat="server"/>
            </ItemTemplate>

If you have a Image as an ItemTemplate in the datagrid.

In the ItemDataBound event of the datagrid call the "HttpHandler" to display the image.In the below code I am finding the image control and assinging the imageUrl as the HttpHandler file path.I am also passing the id as querystring to the HttpHandlerFile.

        System.Web.UI.WebControls.Image photoImage = (System.Web.UI.WebControls.Image)e.Item.FindControl("imgPhoto");
        photoImage.ImageUrl = "ImageHandler.ashx?PhotoID=" + id.ToString();

And in the HttpHandler file use Linq to retrive the Image and display it.

public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "image/jpeg";

    int photoId = -1;
    //Check the query string.
    if (context.Request.QueryString["PhotoId"] != null && context.Request.QueryString["PhotoId"] != "")
    {
        photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
    }

    if (photoId != -1)
    {
        MovieDataContext db = new MovieDataContext();
        //Get the movie record based on the ID
        MovieTable movie = db.MovieTables.First(m => m.ID == photoId);

        System.Data.Linq.Binary fileBinary = movie.Photo;
        byte[] fileByte = fileBinary.ToArray();
        //displays the Image.
        context.Response.BinaryWrite(fileByte);
    }
}

As this HttpHandler file is mapped to the imageURL in the datagrid , you can see the images displayed in the datagrid.