Search This Blog

Friday, March 18, 2011

Display Image in Gridview using Linq


//=============display Image in Gridview ==================
            var data1 = (from m in lnkobj.Members
                        join u in lnkobj.UsrMsts on m.User_id equals u.User_Id
                       where m.Bod == Bod
                        select new
                        {                          
                            u.User_Id
                        });
            int userid=0;
            foreach (var a in data1)
            {
                userid = a.User_Id;
            }

            for (int i = 0; i < GridView2.Rows.Count; i++)
            {
                Image img = (Image)GridView2.Rows[i].Cells[0].FindControl("Image1");
                
                img.ImageUrl = "~/Handler.ashx?Id=" + userid.ToString();
            }
       
        }



//=======================Copy this code into Handler.ashx file ===================
=============================================================================
<%@ WebHandler Language="C#" Class="Handler" %>

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

using System.Web.UI;

using System.Web.UI.WebControls;


public class Handler : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        string id = context.Request.QueryString["Id"];

        context.Response.ContentType = "image/jpeg";

        System.IO.Stream strm = ShowEmpImage(id);

        byte[] buffer = new byte[4096];

        int byteSeq = strm.Read(buffer, 0, 4096);

        while (byteSeq > 0)
        {

            context.Response.OutputStream.Write(buffer, 0, byteSeq);

            byteSeq = strm.Read(buffer, 0, 4096);
        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }
    public System.IO.Stream ShowEmpImage(string id)
    {

        DataClassesDataContext context1 = new DataClassesDataContext();

        var r = (from a in context1.Emps where a.Id ==Convert.ToInt32(id) select a).First();

        return new System.IO.MemoryStream(r.Photo.ToArray());



    }

}

No comments: