Home > other >  Display default image or image in bytes in datalist - asp.net
Display default image or image in bytes in datalist - asp.net

Time:10-31

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!

CodePudding user response:

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:

ImageUrl='<%# "data:image/jpg;base64,"   Eval("image") != null ? Convert.ToBase64String((byte[])Eval("image")) : Convert.ToBase64String(GetDefaultImage()) %>'

That is assuming that Eval("image") is returning null? If possible, it would be ideal to move the call to Eval() 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 like GetDefaultImage() to return a byte array with your default image.

CodePudding user response:

This is what I used to solve the problem in the end :)

ImageUrl='<%# !string.IsNullOrEmpty(Eval("image").ToString()) ? "data:image/jpg;base64,"   Convert.ToBase64String((byte[])Eval("image")) : "/Images/blank.png" %>' />
  • Related