在asp.net中从数据库动态设置图像URL

时间:2014-12-18 10:22:48

标签: asp.net

我想检查代码 DataBinder.Eval(Container,“DataItem.Product.ImageName”)是否为空,然后设置src =“”

 <asp:Image ID="ImgProd" src='<%# string.Format("~/ProductImages/{0}{1}",DataBinder.Eval(Container, "DataItem.Product.ImageName"),".jpg")%>' runat="server" Width="100px" Height="100px" />

如何做到这一点任何人都可以帮助我!

2 个答案:

答案 0 :(得分:0)

我将imagecontrol映像在Repeater或类似的数据绑定控件中:

ASCX / ASPX:

<asp:Repeater ID="myrepeater" OnItemDataBound="MyrepeaterItemDataBound" runat="server">
    <ItemTemplate>
        ...
        <asp:Image ID="ImgProd" runat="server" Width="100px" Height="100px" />
    </ItemTemplate>
</asp:Repeater>

代码隐藏:

protected void MyrepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var myObject = (MyDataSourceObject)e.Item.DataItem;
        var image = (Image)e.Item.FindControl("ImgProd");
        if(!string.IsNullOrEmpty(myObject.Product.ImageName))
        {
            image.ImageUrl=string.Format("~/ProductImages/{0}.jpg", myObject.Product.ImageName );           
        }
    }
}

答案 1 :(得分:0)

谢谢所有我得到了这个:)

<asp:Image ID="ImgProd" src='<%# DataBinder.Eval(Container, "DataItem.Product.ImageName")!=""?string.Format("../../ProductImages/{0}{1}",DataBinder.Eval(Container, "DataItem.Product.ImageName"),".jpg"):""%>' runat="server" Width="100px" Height="100px" />