D B
D B

Reputation: 306

Display data from database in src image in ASP.NET

I have a database that stores the images file name. For example image1.jpg

The actual image is saved in a folder in the root directory in the /images folder.

I want to retrieve the file name and to add it to the image code in ASP.net

<asp:Image ID="VegImg1" runat="server" Height="146px" Width="274px" />

I currently have code calling in its information but unsure how to call in the image and use that as its filepath.

C#

private void loadRecipe()
        {
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True ORDER BY NEWID()");
            con.Open();
            try
                {
                    //Fetching top recipe     
                    SqlDataAdapter sda = new SqlDataAdapter("Select top 1 percent Recipe_Name, Recipe_Description FROM Recipe", con);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);

                    if (dt.Rows.Count > 0)
                        VeganLbl1.Text = dt.Rows[0][0].ToString();
                        descriptionLbl1.Text = dt.Rows[0][1].ToString();

                }
            catch (Exception)
                {



                }

            con.Close();
        }

ASP.NET

 <li class="three">
            <h5>Vegan Recipes<br />
            </h5>
            <table style="width:100%">
              <tr>
                <td class="auto-style5">
                    <asp:Label ID="VeganLbl3" runat="server" Text="Label"></asp:Label>
                  </td>
                <td class="auto-style2">&lt;Link Here&gt;</td>      
              </tr>
              <tr>
                <td class="auto-style6">
            <asp:Image ID="VegImg3" runat="server" Height="146px" Width="274px" />
                  </td>
                <td>
                    <asp:Label ID="descriptionLbl3" runat="server" Text="Label"></asp:Label>
                  </td>     
              </tr>
            </table>
            <br />
            <br />
        </li>

Upvotes: 1

Views: 1105

Answers (1)

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

Assuming That Image is store in same table

SqlDataAdapter sda = new SqlDataAdapter("Select top 1 percent Recipe_Name, Recipe_Description,ImageColumnName FROM Recipe", con);

After Fetching ImageNameColumn Value

if (dt.Rows.Count > 0)
 {
       VeganLbl1.Text = dt.Rows[0][0].ToString();
       descriptionLbl1.Text = dt.Rows[0][1].ToString();
       VegImg1.ImageUrl=String.Format("//Image//{0}",dt.Rows[0][2].ToString());
 }

Upvotes: 2

Related Questions