Display Image from database based on ID using C# and VB.Net in ASP.Net

Last Reply 6 months ago By dharmendr

Posted 6 months ago

How to display image from folder using image id in sql table in asp.net

You are viewing reply posted by: dharmendr 6 months ago.
Posted 6 months ago

Hi Faizal,

Check this example. Now please take its reference and correct your code.


<asp:TextBox runat="server" ID="txtId" />
<asp:Button Text="Search" ID="btnSearch" OnClick="Search" runat="server" />
<br />
<asp:Image ID="imgPhoto" ImageUrl="" runat="server" Visible="false" />



protected void Search(object sender, EventArgs e)
    imgPhoto.Visible = true;
    System.Data.DataRow[] dr = GetData().Select("Id=" + txtId.Text.Trim());
    if (dr.Length > 0)
        imgPhoto.ImageUrl = dr[0]["Path"].ToString();
        imgPhoto.AlternateText = dr[0]["Name"].ToString();
        imgPhoto.ImageUrl = "Images/NoImage.jpg";
        imgPhoto.AlternateText = "Image not available.";

private System.Data.DataTable GetData()
    System.Data.DataTable dt = new System.Data.DataTable();
    dt.Columns.AddRange(new System.Data.DataColumn[3] { 
                        new System.Data.DataColumn("Id", typeof(int)),
                        new System.Data.DataColumn("Name", typeof(string)),
                        new System.Data.DataColumn("Path",typeof(string)) });
    dt.Rows.Add(1, "Chrysanthemum", "Images/Chrysanthemum.jpg");
    dt.Rows.Add(2, "Desert", "Images/Desert.jpg");
    dt.Rows.Add(3, "Hydrangeas", "Images/Hydrangeas.jpg");
    dt.Rows.Add(4, "Jellyfish", "Images/Jellyfish.jpg");

    return dt;


Protected Sub Search(ByVal sender As Object, ByVal e As EventArgs)
    imgPhoto.Visible = True
    Dim dr As System.Data.DataRow() = GetData().Select("Id=" & txtId.Text.Trim())
    If dr.Length > 0 Then
        imgPhoto.ImageUrl = dr(0)("Path").ToString()
        imgPhoto.AlternateText = dr(0)("Name").ToString()
        imgPhoto.ImageUrl = "Images/NoImage.jpg"
        imgPhoto.AlternateText = "Image not available."
    End If
End Sub

Private Function GetData() As System.Data.DataTable
    Dim dt As System.Data.DataTable = New System.Data.DataTable()
    dt.Columns.AddRange(New System.Data.DataColumn(2) {
                        New System.Data.DataColumn("Id", GetType(Integer)),
                        New System.Data.DataColumn("Name", GetType(String)),
                        New System.Data.DataColumn("Path", GetType(String))})
    dt.Rows.Add(1, "Chrysanthemum", "Images/Chrysanthemum.jpg")
    dt.Rows.Add(2, "Desert", "Images/Desert.jpg")
    dt.Rows.Add(3, "Hydrangeas", "Images/Hydrangeas.jpg")
    dt.Rows.Add(4, "Jellyfish", "Images/Jellyfish.jpg")
    Return dt
End Function