I currently retrieve data from a database and store it in a data list. One of those items is a bytes value that is used to display an image. The code works, however, when there is no image available, I run into an error as a result of trying to perform operations on a null value. Is there any way to to display a default image, such as that found in the imageButton below the one in question, if there is no value in the image field of the database?
<asp:DataList ID="applicationsDataList" runat="server" RepeatColumns="4" OnItemCommand="itemCommand" >
<ItemTemplate>
<table>
<tr>
<td>
<asp:ImageButton ID="userImage" CssClass="cardImage" CommandName="profile" runat="server" ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("image")) %>'/>
<%--<asp:ImageButton CssClass="cardImage" CommandName="profile" runat="server" ImageUrl="/Images/blank.png"/>--%>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Thanks geniuses!
3
Answers
This is what I used to solve the problem in the end :)
You can use C#’s ternary operator to check whether the value is null, and insert a base64 string for the default image instead.
Something like this:
That is assuming that
Eval("image")
is returningnull
? If possible, it would be ideal to move the call toEval()
outside of the expression so that you don’t call it twice (once in the condition, and once in the consequence). You can then define a function likeGetDefaultImage()
to return a byte array with your default image.You could as noted work on a more "complex" expression. But then again?
I often just write code in the on-data bound event.
so, with this:
Then just put the above in the data bound. It somewhat of a wash out in terms of say having to write a few extra lines of code in item data bound, or having a hard to read messy expression in the markup? (I am open to flipping a coin on this).
But, item data bound then becomes this:
Note how we are able to get the data bind row values. That data set ONLY persists during the data binding events – after done, it goes out of scope.