ASP.NET Repeater Question

I have repeater control and under ItemTemplate, I have image control. Anyway old

How can I install ImageUrl programmatically?

In any case, the old html code I had was like this:

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

But I want to check if the image exists in the directory or not, then I can configure using a temporary image.

I have a code, but .. it does not work, so it makes no sense to show it here. Can you guys help me? Should I use the ItemCreated or ItemDataBound event?

+4
source share
5 answers

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

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

You need the appropriate method in the above code publicly:

 public string MyImageUrlFunction(string field) { // put some logic here to determine url return imageUrl; } 
+4
source

In ItemDataBound do the following:

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

These are System.Web.UI.HtmlControls.HtmlImage , System.Web.UI.DataBinder and System.IO.File .

+3
source

ItemDataBound. You can get the control link through the current findcontrol event, and then check that the image exists. You can get the file path using Server.MapPath ("~ / images / test.png"), and then if that doesn't happen, enter your own.

You can also use a public method that client-side markup can call, pass a URL, and provide a default value if it does not exist.

NTN.

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

for mistake

Server tag not formed correctly

You must remove the extra space in your code!

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

All Articles