How to display binary images into a gridview in ASP.NET using C#?

后端 未结 2 744
别那么骄傲
别那么骄傲 2020-12-01 23:06

I want to display binary images into a gridview named \'gvExistedCharacter\'. I did research about it and many of them suggested to use a handler. However, I have no idea ho

2条回答
  •  长情又很酷
    2020-12-01 23:24

    You can use handler to display image in gridview , your html markup look like inside

    Gridview ItemTemplate set image control src as src=~/ShowImage.ashx?id=" + id

    where ShowImage.ashx is your handler which return MemoryStream((byte[])img);

    Here my one similar article how to get binary data and display as image

    Blog Article: Convert Binary data to image, Save and retrieve image from binary data asp.net c#

    In your case your querystring is characterID

    so your image src would be src=~/ShowImage.ashx?id=" + characterID


    Updated Answer:

    Html Markup:

    
        
            
                
                    
                
            
            
                
                    
                
            
            
                
                    
                
            
        
    
    

    Code behind:

    protected void Page_Load(object sender, EventArgs e)
    {        
        DataTable dt = getData();
        GridView1.DataSource = dt;
        GridView1.DataBind();
      }
    
    public  DataTable getData() 
    {
      SqlDataAdapter dap = new SqlDataAdapter("select characterID,blueBallImage,gameLevel from CorrespondingBall", cn);
      DataSet ds = new DataSet();
      dap.Fill(ds);
      return ds.Tables[0];
    }
    

    Generic handler: Add new generic handler here showIamges.ashx is my generic handler

    public void ProcessRequest(HttpContext context)
     {
        Int32 my_Id;
        if (context.Request.QueryString["getID"] != null)
        {
           my_Id = Convert.ToInt32(context.Request.QueryString["getID"]);
           context.Response.ContentType = "image/jpeg";
           Stream strm = ShowEmpImage(my_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 Stream ShowEmpImage(int my_Id)
    {
       string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
       SqlConnection connection = new SqlConnection(conn);
       string sql = "select blueBallImage from CorrespondingBall WHERE characterID = @ID";
       SqlCommand cmd = new SqlCommand(sql, connection);
       cmd.CommandType = CommandType.Text;
       cmd.Parameters.AddWithValue("@ID", my_Id);
       connection.Open();
       object img = cmd.ExecuteScalar();
       return new MemoryStream((byte[])img);
     }
    

提交回复
热议问题