how to show image2 in gridview

RAVI 1,056 Reputation points
2024-05-29T13:35:22.69+00:00

Hello

This is my aspx page

   <asp:TemplateField HeaderText="IMAGE1">
            <ItemTemplate>
                <asp:Image ID="Image1" runat="server" />
            </ItemTemplate>
            <HeaderStyle ForeColor="Red" />
        </asp:TemplateField>

   <asp:TemplateField HeaderText="IMAGE2">
            <ItemTemplate>
                <asp:Image ID="Image2" runat="server" />
            </ItemTemplate>
            <HeaderStyle ForeColor="Red" />
        </asp:TemplateField>

This is my gridivew databound

 protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
    {


        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            
            Uri uri = Request.Url;

            //Generate Absolute Path for the Images folder.
            string applicationUrl = string.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, uri.AbsolutePath);
            applicationUrl = applicationUrl.Replace(Request.Url.Segments[Request.Url.Segments.Length - 1], "");

            //Fetch the Image ID from the DataKeyNames property.
            int id = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Values[0]);

            //Generate and set the Handler Absolute URL in the Image control.
            string imageUrl = string.Format("{0}Handler.ashx?id={1}", applicationUrl, id);
            (e.Row.FindControl("Image1") as System.Web.UI.WebControls.Image).ImageUrl = imageUrl; 

             
        }


 
    }

This handler

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        int id = 0;
        int.TryParse(context.Request.QueryString["id"], out id);
        if (id > 0)
        {
            string constr = ConfigurationManager.ConnectionStrings["CHEMIMSConnectionString"].ConnectionString;             using (SqlConnection con = new SqlConnection(constr))             {                 string query = "SELECT Data,Datatwo FROM tblFiles_New WHERE Id =" + id;                 using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
                {
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        byte[] bytes = (byte[])dt.Rows[0]["Data"];                                                   
                        context.Response.BinaryWrite(bytes);
                        context.Response.End();
 
                    }
                }
            }
        }
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

how to show Datatwo in Image2

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,542 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,071 Reputation points Microsoft Vendor
    2024-05-31T05:44:09.3166667+00:00

    Hi @RAVI,

    You can serialize the two image data into json in Handler.

    Create a Test class:

     public class Test
     {
         
         public byte[] Data { get; set; }
         public byte[] Datatwo { get; set; }
     }
    
    public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            int id = 0;
            int.TryParse(context.Request.QueryString["id"], out id);
            if (id > 0)
            {                           
                string json = this.GetCustomersJSON(id);             
                context.Response.ContentType = "application/json";
                context.Response.Write(json);
            }
        }
        private string GetCustomersJSON(int customerId)
        {
            List<Test> customers = new List<Test>();
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["CHEMIMSConnectionString"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {                   
                    cmd.CommandText = "SELECT Data,Datatwo FROM tblFiles_New WHERE Id = @Id";
                    cmd.Parameters.AddWithValue("@Id", customerId);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            customers.Add(new Test()
                            {
                              
                                Data = (byte[])sdr["Data"],
                                Data1 = (byte[])sdr["Datatwo"]
                            });
                        }
                    }
                    conn.Close();
                }
                return (new JavaScriptSerializer().Serialize(customers));
                
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         Uri uri = Request.Url;
         //Generate Absolute Path for the Images folder.
         string applicationUrl = string.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, uri.AbsolutePath);
         applicationUrl = applicationUrl.Replace(Request.Url.Segments[Request.Url.Segments.Length - 1], "");               
         //Fetch the Image ID from the DataKeyNames property.
         int id = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Values[0]);
         //Generate and set the Handler Absolute URL in the Image control.
         var imageUrl = string.Format("{0}Handler.ashx?id={1}", applicationUrl, id);
         string responseData = (new WebClient()).DownloadString(imageUrl);                
         var obj = new JavaScriptSerializer().Deserialize<List<Test>>(responseData);
         byte[] image1 = obj[0].Data;
         byte[] image2 = obj[0].Datatwo;
         string base64String1 = Convert.ToBase64String(image1, 0, image1.Length);
         string base64String2 = Convert.ToBase64String(image2, 0, image2.Length);
         (e.Row.FindControl("Image1") as System.Web.UI.WebControls.Image).ImageUrl = "data:image/png;base64," + base64String1;
         (e.Row.FindControl("Image2") as System.Web.UI.WebControls.Image).ImageUrl = "data:image/png;base64," + base64String2;
     }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.