5

I am trying to set the visible property for a label to either true or false depending on a condition. This is in ASPX page. I am doing something wrong and getting error when this is executed.

<td><asp:Label ID="Label23" runat="server" Text='CERTIFIED'
   Visible='<%# DataBinder.Eval(Container.DataItem, "IsAuthorized") > 0%>'>
</asp:Label></td>

Error I am getting is below.

Compiler Error Message: CS0019: Operator '>' cannot be applied to operands of type 'object' and 'int'

What changes need to be done?

All I need to do set the visible property of the LABEL to true when 'IsAuthorized' is greater than zero.

M4N
  • 94,805
  • 45
  • 217
  • 260
Anirudh
  • 581
  • 5
  • 14
  • 32

5 Answers5

12

That's because you have a syntax error, you silly bunny.

Here you are, it should be like this:

 <td><asp:Label ID="Label23" runat="server" Text='CERTIFIED' Visible='<%# DataBinder.Eval(Container.DataItem, "IsAuthorized") %>'  /></td>

You had an extra > and a 0 in there somewhere. Also, since you aren't doing anything between the <asp:Label and </asp:Label>, you can close it with an end slash and skip a separate ending tag. Like this <asp:Label ... />

ALSO, sometimes trying to set a visible property like that causes problems, the program can complain that the value wasn't a Boolean. You might want to also ad an explicit conversion like this:

 Visible='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "IsAuthorized")) %>' 
rlb.usa
  • 14,942
  • 16
  • 80
  • 128
  • 2
    This is a beautiful answer! From silly bunny, to the corrected line of code, to the explanation of the correction, and then at the end "you might also want to". This is the perfect formula for an answer - 1) answer, 2) explain, 3) improve. – CindyH Jun 27 '17 at 16:11
5

Assuming that IsAuthorized is a bit type, just cast it to a boolean:

 Visible='<%#Convert.ToBoolean(Eval("IsAuthorized"))%>'  
James Johnson
  • 45,496
  • 8
  • 73
  • 110
2

Note on a server side control you can do this:

<someControl id="myId" runat="server" Visible='<%# this.SomeField > 5 %>'>

But it won't work unless you call DataBind in the code behind, such as in Page_Load:

myId.DataBind():
AaronLS
  • 37,329
  • 20
  • 143
  • 202
1

Assuming IsAuthorized is an integer, you should use this:

Visible='<%# ((int)DataBinder.Eval(Container.DataItem, "IsAuthorized")) > 0 %>'

Eval returns an object, so you have to cast it to an integer first.

M4N
  • 94,805
  • 45
  • 217
  • 260
0
<td><asp:Label ID="Label23" runat="server" Text='CERTIFIED' Visible='<%# (int)(DataBinder.Eval(Container.DataItem, "IsAuthorized")) > 0 %>' ></asp:Label></td>
Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68