views:

63

answers:

4

Hi guys,

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?

+3  A: 

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;
}
Joel Etherton
Error 4 The server tag is not well formed.
Nullstr1ng
ok I got it working. But there's an error in your code. There shouldn't be a semicolon at the end :) but thanks Joel!
Nullstr1ng
@Nullstr1ng - sorry about that. I didn't have access to my IDE and I've been hopping back and forth between vb and c# so my ; finger is a little trigger happy.
Joel Etherton
+1  A: 

Hey,

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.

Brian
+2  A: 

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.

Dan Dumitru
this one looks great too! thanks Dan
Nullstr1ng
+1  A: 
<ItemTemplate>
    <asp:Image ImageUrl='<%# System.IO.File.Exists(Eval("ImageSourceProperty").ToString()) ? Eval("ImageSourceProperty").ToString() : TemporaryImagePath %>' runat="server" />
</ItemTemplate>
BlueCode
Error 4 The server tag is not well formed.
Nullstr1ng