Tuesday, January 17, 2012

How to Store and Display Image in Image Control

Some Times happens that we tries to Show in Image in Box using Image controls. Developes use different Kinds of Stretegies like to store the Photoes in Folder and Load Photo from this Folder. But It does not works Sometimes. The better way is to store image in database in Binary Format and show it on web page. Now How can we do it given below Steps:
1. Make Page Named Picture.aspx and Write this Code on its Load Event.



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim conn As New SqlConnection(ConfigurationManager.AppSettings("ConnectionKoris"))
Dim sql1 As String = "Select Image from Product_master where Product_id='" & Request.QueryString("id") & "'"
        
 Dim cmd1 As New SqlCommand(sql1, conn)
 conn.Open()
        
 Dim dr As SqlDataReader = cmd1.ExecuteReader()
         
 If dr.Read() Then
            If dr("Image").ToString() <> System.DBNull.Value.ToString() Then
                
 Dim imageByte As Byte() = DirectCast(dr("Image"), Byte())
 If imageByte IsNot Nothing AndAlso imageByte.Length > 0 Then
                    Context.Response.ContentType = "image/jpeg"
                    Context.Response.BinaryWrite(imageByte)
                End If
            End If
        End If
        dr.Close()
        conn.Close()
    End Sub
How to Pass from Code Behind:
Note: TxtProdId.text is the Id of database table in which favor particulare image is contained.
ProdImg.ImageUrl = "Picture.aspx?id=" & Val(TxtProdId.Text)
How to Pass for bind in Gridview,Datalist,ListView,Datagrid etc. as Given Below: 

<asp:Image ID="Image2" runat="server" Height="80px" ImageUrl='<%# "Picture.aspx?id=" & Eval("Product_id")%>' Width="80px" />

No comments:

Post a Comment