Display image in gridview from database?

I have images saved in a SQL Server database as binary data. Now I want to show these images in a gridview. But there is web control that directly reads data from the database. To manage web images, the ImageUrl property is ImageUrl , so it cannot be used because my images are in databases. However, I can store the images in a folder, but I need another way that directly reads the image data from the database and shows it in the grid.

0
gridview
source share
2 answers

using a universal handler, you can convert binary data to an image and display it

Code: Set the image management URL as Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

where ShowImage.ashx is the common handler file.

 using System; using System.Configuration; using System.Web; using System.IO; using System.Data; using System.Data.SqlClient; public class ShowImage : IHttpHandler { public void ProcessRequest(HttpContext context) { Int32 empno; if (context.Request.QueryString["id"] != null) empno = Convert.ToInt32(context.Request.QueryString["id"]); else throw new ArgumentException("No parameter specified"); context.Response.ContentType = "image/jpeg"; Stream strm = ShowEmpImage(empno); 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); } //context.Response.BinaryWrite(buffer); } public Stream ShowEmpImage(int empno) { string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; SqlConnection connection = new SqlConnection(conn); string sql = "SELECT* FROM table WHERE empid = @ID"; SqlCommand cmd = new SqlCommand(sql,connection); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ID", empno); connection.Open(); object img = cmd.ExecuteScalar(); try { return new MemoryStream((byte[])img); } catch { return null; } finally { connection.Close(); } } } 

Blog article: Save and get an image from asp.net C # binary data

+2
source share
0
source share

All Articles