Set value for 'visible' property in ASPX page programatically - asp.net

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.

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")) %>'

Assuming that IsAuthorized is a bit type, just cast it to a boolean:
Visible='<%#Convert.ToBoolean(Eval("IsAuthorized"))%>'

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():

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.

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

Related

suppress unit display in label

I usually use this syntax to display the unit symbol in a label: ej. 5'230 €
<asp:Label runat="server" Text='<%# Eval("TotalAmount","{0:#,###.##} €") %>' id="LabelTotal"/>
The ugly thing about is that the symbol is displayed even if the value is null or empty. Then I would like the symbol just to be suppressed.
Anyone has an idea how to do that?
Martin
You can use the following snippet
<asp:Label runat="server" Text='<%# Convert.ToDecimal(Eval("TotalAmount")) > 0 ? string.Format("{0:C}", Convert.ToDecimal(Eval("TotalAmount"))) : string.Empty %>' id="LabelTotal"/>
If the value that is to be evaluated can contain null values, you need to check for IsNullOrEmpty first before conversion.
<asp:Label runat="server" Text='<%# !string.IsNullOrEmpty(Eval("TotalAmount").ToString()) ? Convert.ToDecimal(Eval("TotalAmount")) > 0 ? string.Format("{0:C}", Convert.ToDecimal(Eval("TotalAmount"))) : string.Empty : string.Empty %>' id="Label1"/>

Calling a property or member function of a string object inside of a ListView

I'm having some trouble calling a property or a method on a databound string object inside of a ListView. See this example:
<asp:ListView runat="server" ID="FullInfoListView">
<LayoutTemplate>
<table class="tablestripe" width="100%">
<asp:Placeholder runat="server" ID="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr valign="top" runat="server" Visible='<%# !string.IsNullOrEmpty((string)Eval("Phone")) %>'>
<td><strong>Phone:</strong></td>
<td><span runat="server" Visible='<%# ((string)Eval("Phone")).Length == 4 %>'>x</span><%# Eval("Phone") %></td>
</tr>
</ItemTemplate>
</asp:ListView>
This line:
<%# ((string)Eval("Phone")).Length == 4 %>'>
is what is giving me trouble. If I remove the .Length everything works fine. If I leave it in there my code throws an "Object reference not set to an instance of an object." exception on the line where I call the DataBind() method on the ListView in my code behind. This same behavior occurs with .ToLower() as well.
EDIT
I think I got this figured out. Thanks for those of you who suggested moving this out to a method in the code behind to help with debugging. The problem was related to a null reference...go figure :) I thought that if the table row wasn't visible that none of the logic inside would get evaluated, but I think due to the fact that it is databound the logic is evaluated anyway. So simply changing the above line to the following fixed the problem:
<%# Eval("Phone") != null && ((string)Eval("Phone")).Length == 4 %>'>
I would consider using a Label instead of a <span>. Instead of casting it to string, just use the ToString() function instead, and wrap the entire expression in parentheses to ensure that it's evaluating as a boolean:
<asp:Label ID="Label1" runat="server" Visible='<%# (Eval("Phone").ToString().Length >= 4) %>' Text="X" />
If the above doesn't fix your problem, you can always add a method in the code behind to do this:
<asp:Label ID="Label1" runat="server" Visible='<%# CheckLength(Eval("Phone").ToString()) %>' Text="X" />
Code-behind:
public bool CheckLength(string value)
{
return value.Length >= 4;
}
Move the compound code to code-behind method. For example the
'<%# ((string)Eval("Phone")).Length == 4 %>'
becomes
'<%# IsPhoneSpanVisible( (string)Eval( "Phone" ) ) %>'
with
protected bool IsPhoneSpanVisible( string Phone )
{
// provide your logic here
}
This way you'll be easily able to debug your code.

How do I set the Visible attribute in an ItemTemplate?

<asp:TemplateField HeaderText="Audio">
<ItemTemplate>
<asp:Image ID="playImage" runat="server"
ImageUrl="~/images/nextpg.gif"
Visible='<%# (Eval("available")=="Y") ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
In my query I am returning the "available" column which is populated with a letter of Y or N. For some reason the evaluation of this expression is never true. If I change it to != instead of == it will always be true. That leads me to believe the Eval("available")=="Y" is simply not evaluating as expected.
After much messing around, this finally worked:
<%# ((String)Eval("available")).Equals("Y") ? true : false %>
The issue seems to be that you can't use == but instead you must use the String.Equals() method. I'm not sure why but that's just the way it is.

Can I negate the value in an attribute that uses an "Eval"?

I'd like to set a button's enabled state to be the negation of a value.
So given this code:
<asp:CheckBox ID="DefaultChecked"
Checked='<%# Bind("IsDefaultMessage") %>'
Enabled="false"
runat="server" />
<asp:LinkButton ID="MakeDefaultButton"
runat="server"
CommandName="MakeDefault'
CommandArgument='<%# Bind("ResidentialInfoID") %>'
Text="Make Default" />
How can I make the LinkButton Enabled attribute false if IsDefaultMessage == true?
Use Eval instead of Bind. Bind is for two-way binding, i.e. for cases where you need to be able to save the data back to your data source.
When you use Bind, the compiled page will actually have generated code that uses Eval to set the value, plus some code to read out the value for saving. Because Bind is replaced with generated code, you can't use any extra logic with Bind.
<asp:CheckBox ID="DefaultChecked" Checked='<%# !(bool)Eval("IsDefaultMessage") %>' Enabled="false" runat="server" />
<asp:LinkButton ID="MakeDefaultButton" runat="server" CommandName="MakeDefault' CommandArgument='<%#Bind("ResidentialInfoID") %>' Text="Make Default"/>
If you can use Eval, it is just a method of the Control class. It's only special in that it needs to be in the context of a data bound block <%# ... %>. Other than that, you can basically treat the block like a regular <%= %> expression block:
<%# !(bool)Eval("IsDefaultMessage") %>
If you want to still Bind it (Eval isn't round-trip), than you'll need to negate it back and forth during databinding. You may not need to do this though, if you can just re-word the control. For example, if a check box, instead of labelling it "Is Not Default Message" to the user and negating it back and forth, than lable it "Is Default Message". Contrived example, but you get the idea.
In case someone is looking for an option with VB.Net
<asp:CheckBox ID="DefaultChecked" Checked='<%# NOT (Eval("IsDefaultMessage")) %>' Enabled="false" runat="server" />
I've never used Bind but my understanding is that it is similar to Databinder.Eval. Either way, both methods return objects so you need to cast it to a boolean before evaluating it.
<%# !Convert.ToBoolean(Bind("IsDefaultMessage") %>
Edit: Looks like this can't be done and using a SqlDataSource on the page would solve the problem. http://forums.asp.net/t/1009497.aspx.
As I recall (It's been a while), there's no particular magic in <%#Bind(. It's just #Bind( inside <%....%>. Which means you'd want:
<% ! #Bind("IsDefaultMessage") %>'
The code
Checked='<%# Eval("IsDefaultMessage").ToString().Length() > 4 %>'
will return true if IsDefaultMessage is false
Since "False".Length = 5 and "True".Length = 4

Formatting DataBinder.Eval data

How can I format data coming from a DataBinder.Eval statement in an ASPX page?
For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.
The code for this goes like this:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error?
If this is not possible, is there a way to do inline formatting?
There is an optional overload for DataBinder.Eval to supply formatting:
<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>
The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:
<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>
After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.
The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.
So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:
default.aspx
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
default.aspx.cs code:
public partial class _Default : System.Web.UI.Page
{
protected string GetDateInHomepageFormat(DateTime d)
{
string retValue = "";
// Do all processing required and return value
return retValue;
}
}
Hope this helps others as well.
Why not use the simpler syntax?
<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>
This is the template control "Eval" that takes in the expression and the string format:
protected internal string Eval(
string expression,
string format
)
http://msdn.microsoft.com/en-us/library/3d2sz789.aspx
You can use a function into a repeater like you said, but notice that the DataBinder.Eval returns an object and you have to cast it to a DateTime.
You also can format your field inline:
<%# ((DateTime)DataBinder.Eval(Container.DataItem,"publishedDate")).ToString("yyyy-MMM-dd") %>
If you use ASP.NET 2.0 or newer you can write this as below:
<%# ((DateTime)Eval("publishedDate")).ToString("yyyy-MMM-dd") %>
Another option is to bind the value to label at OnItemDataBound event.
This line solved my problem:
<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>
To format the date using the local date format use:
<%#((DateTime)Eval("ExpDate")).ToString("d")%>
How to Format an Eval Statement to Display a Date using Date Locale
Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.
Mark Up:-
<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>
Code behind:-
Public Function fLabel(ByVal tval) As String
fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function
Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'
This works for the format as you want
<asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
</asp:Label>
You can use it this way in aspx page
<%# DataBinder.Eval(Container.DataItem, "DateColoumnName", "{0:dd-MMM-yyyy}") %>

Resources