Search code examples
c#asp.netsql-servercastingeval

Casting Eval("bitValue") as Bool


I have a list view with a HyperLink control within the ItemTemplate. I want to display the link if a returned value is 0 (false), and not display the link if it is 1 (true).

So far I have this:

<asp:HyperLink runat="server" ID="lnkReview"
  NavigateUrl='<%# Eval("EnquiryID", @"selectcompany.aspx?enq={0}")%>'
  Text="Review Enquiry"
  Visible='<%# ((bool)Eval("Locked"))==true? false : true %>' />

...but this renders an 'Specified cast is not valid' exception.

Examples I've seen elsewhere suugest this should work. I can confirm that the Locked column only returns 0 or 1 (from SQL Server) - surely these should be easily cast from bit/int to bool??


Solution

  • If Locked is an int you should do this:

    <%# ((int)Eval("Locked")) == 1 ? true : false %>
    

    But then this should work too, so it returns true when Locked > 0

    <%# !((int)Eval("Locked") == 0) %>
    

    No matter it is mentioned that Locked contains 0 or 1. It is still an INT which can for some reason contain values > 1. Therefore i find it good practice to do the check on == 0 instead of == 1. We don't know what Locked is used for and in the future the design could change so that Locked can contain a value > 1.