views:

94

answers:

3

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??

A: 

Give this a try:

bool.Parse(Eval("Locked").ToString())
spinon
Looks like two unnecessary conversions: int to string, string to bool.
Jeroen
Anti-pattern. Do not use!
leppie
+2  A: 

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.

Jeroen
`((int)Eval("Locked")) == 1` is sufficient.
leppie
I could swear I actually tried this. The confusing part is that the field is actually a bit and therefore cannot be > 1, therefore I expected to be able to cast it to bool. Still, treating it as an int works, and that is the important thing! Thanks.
CJM
@leppie - `((int)Eval("Locked"))!=!` - nobody seems to spotted, the logic was reversed... but point taken.. :)
CJM
This solution does not work for me. Why does it seem to work for everyone else? I'm having trouble figuring out if the op started with an int or a bit in the database. I'm starting with a bit.
Joe Philllips
This ended up being what my solution looked like: `<%# ((bool)Eval("default")) == false %>`
Joe Philllips
+1  A: 

SQL is a strange world where bits can have three states 0, 1 and null! So this means that Eval("Locked") is a nullable type bool, not a plain bool A cast to bool will not be valid if the bit value is null, you have to check that first:

(Eval("Locked")!=null && (bool)Eval("Locked")==true)

This assumes that null should be mapped to false.

Gnomo
Are you sure? There should be no problem casting a `bool?` to `bool` if there are no null values (as confirmed by the OP).
Gabe
Oh! I missed the confirmation that there are no null values...
Gnomo
Forgetting the issue of null values, your solution won't work because it won't allow a bit to be cast as a bool for some unknown reason...
CJM