在ASP.NET中的src映像中显示数据库中的数据

时间:2016-04-15 11:49:28

标签: c# sql asp.net

我有一个存储图像文件名的数据库。例如image1.jpg

实际图像保存在/images文件夹的根目录下的文件夹中。

我想检索文件名并将其添加到ASP.net中的图像代码

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

我目前在其信息中调用了代码,但不确定如何调用图像并将其用作文件路径。

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>

1 个答案:

答案 0 :(得分:2)

假设图像存储在同一个表中

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

获取ImageNameColumn值

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());
 }