Skip to main content

Display Image from Database Asp.Net

Dynamic Image.
         We can bind image dynamically in asp:image tag. This can be done by using data grid or grid view. Eval function is used to bind data from database. As Table shown below image_url field contain the location of image in server. In this example we use datagrid, the design page sample code below. The asp:image attribute ImageUrl bind value dynamically using Eval function. The Eval function is set with image_url field in image_tb table.

img_tb
 id image_name image_url
 1 img1 ~/images/img1.jpg

 <asp:DataGrid  ID="datagrid1" runat ="server"      font-names="Times New Roman"
font-size="14px" ShowFooter="True" ForeColor="#333399" BorderWidth="1px" BorderColor="Black"
BorderStyle="Solid"     AutoGenerateColumns="False"   AllowPaging ="true"  >
         <Columns >
              <asp:TemplateColumn >
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                     <ItemTemplate >                      
                         <asp:Image ID="gvimg" AlternateText = 'tamilnadu government jobs' runat="server" ImageUrl='<%#Eval("image_url")%>' Visible='<%# IIf(Eval("Image_url") Is DBNull.Value, "False", "True")%>'  Width ="60px" Height ="40px" /> 
                             </div>
                     </ItemTemplate>
</asp:TemplateColumn>
</asp:TemplateColumn>
              <asp:TemplateColumn >
<HeaderStyle ></HeaderStyle>
                     <ItemTemplate >
         </Columns>
     </asp:DataGrid>

In Code Behind Page(Vb.Net)
Dim con As New SqlConnection(strConn)
        id2 = ddd
        Dim strCmd As String = ""
        strCmd += "SELECT "
        strCmd += " * "
        strCmd += "FROM img_tb"
        Dim oDS As New DataSet
        ' Execute the command and add a named table to the dataset
        Dim da As New SqlDataAdapter(strCmd, con)
        con.Open()
        da.Fill(oDS, "ResumeList")
        datagrid1.DataSource = oDS
        datagrid1.DataBind()
        'Close the connection
        con.Close()
In Vb.net code page datagrid1.DataBind() will load entire table value in datagrid.  

How to hide image dynamically if image not found in location 

ImageUrl='<%#Eval("image_url")%>' Visible='<%# IIf(Eval("Image_url") Is DBNull.Value, "False", "True")%>'  Visible attribute of asp image tag is bind using Eval function. We use if operator to check whether the image is found. It will return true if image is found in location or otherwise it return false.



Comments