4
votes

I have a repeater control and under the ItemTemplate, I have Image control. Anyway the old

How can I set the ImageUrl programatically?

Anyway, the old html code I have was like this:

<ItemTemplate>
   <img src="<%# Eval("ImageSource") %>" alt="" />
</ItemTemplate>

But I want to check if the image exists in directory or not then I can setup with temp image.

I have a code but .. it's not really working so there's no sense of showing it here. Can you guys help me? Should I use ItemCreated or ItemDataBound event?

5
It's great to ask here in stackoverflow, you can get the responses and answer immediately, unlike in msdn forums. Thanks guys. - jaysonragasa

5 Answers

4
votes

In the xml side in the template, you need to call a method directly.

<asp:Image runat="server" ID="myImg" ImageUrl='<%# MyImageUrlFunction(Eval("DataFieldName").ToString()); %>' />

You need a corresponding method in the code behind defined publicly:

public string MyImageUrlFunction(string field) 
{
    // put some logic here to determine url
    return imageUrl;
}
2
votes

In your ItemDataBound, do something like:

protected void rpt_ItemDataBound(object sender, RepeaterEventArgs e)
{
    HtmlImage img = (HtmlImage)e.Item.FindControl("img");

    string imageUrl = (string)DataBinder.Eval(e.Item.DataItem, "ImageSource");
    if (File.Exists(imageUrl))
        img.Src = imageUrl;
}

That's System.Web.UI.HtmlControls.HtmlImage, System.Web.UI.DataBinder and System.IO.File.

1
votes

ItemDataBound. You can get the control reference through the current item's findcontrol event, and then check to see that the image exists. You can get the file path using Server.MapPath("~/images/test.png"), and then if it doesn't, inject your own.

You can also use a public method that the client-side markup can call, pass in the URL, and provide a default if it doesn't exist.

HTH.

0
votes
<ItemTemplate>
    <asp:Image ImageUrl='<%# System.IO.File.Exists(Eval("ImageSourceProperty").ToString()) ? Eval("ImageSourceProperty").ToString() : TemporaryImagePath %>' runat="server" />
</ItemTemplate>
0
votes

for the Error

The server tag is not well formed

You should remove extra space in your code!

<%# System.IO.File......%>
should be <%#System.IO.File......%>