If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
This is the first of what I hope will be an ongoing selection of little code snippets that I have either written or found online that I think might be of benefit to others. Generally these will be written in VB.Net and will aimed at .Net 2.0 websites. Although I am currently teaching myself C# so the code could change to that at some point.
Today I had a problem with populating images in a bound data list. I was populating the list from a dataset that was being populated from an XML web service. One of the fields in the source was a path to a hosted imaged. However on some rows in the source data it was possible that the image path could be blank.
Ideally what I wanted to do was replace the blank field with a path to an image on my site, however I had no idea how to do this. Here is a rough example of what my datalist looked like:
<asp:DataList ID="datalist1" runat="server" >
<ItemTemplate>
<a href='Webpage.aspx?RecordID=<%# Eval("id") %>'>
<img src='<%# Eval("thumbnailURL") %>'
alt=' <%# Eval("title") %>' style="border:0;"/>
</a>
</ItemTemplate>
</asp:DataList>
Pretty simple and it worked great as long as the image name was present. I spent some time puzzling over it and tried various things such as editing the dataset, capturing the databound event of the datalist etc. But nothing really seemed to work. Eventually after much head banging I came up with this simple and I thin rather elegant solution.
First of all I created a custom function within my code behind page as such:
Public Function CheckThumbnail(ByVal o As Object)
Dim strReturn As String
If o.ToString = String.Empty Then
strReturn = "/Images/Icons/no-image.jpg"
Else
strReturn = o.ToString
End If
Return strReturn
End Function
Then I just change my ItemTemplate to wrap the Eval code around a call to the function, as below:
<asp:DataList ID="datalist1" runat="server" >
<ItemTemplate>
<a href='Webpage.aspx?RecordID=<%# Eval("id") %>'>
<img src='<%# CheckThumbnail(Eval("thumbnailURL")) %>'
alt=' <%# Eval("title") %>' style="border:0;"/>
</a>
</ItemTemplate>
</asp:DataList>
It works perfectly, if the image name is present it simply passes it back to the page, otherwise it returns the path to a default image hosted on my site. I hope this is of use to anyone out there stuck with the same or similar problem, enjoy.




