If dataitem is Null I want to show 0
<asp:Label ID="Label18" Text='<%# Eval("item") %>' runat="server"></asp:Label>
How can I accomplish this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can also create a public method on the page then call that from the code-in-front.
e.g. if using C#:
public string ProcessMyDataItem(object myValue)
{
if (myValue == null)
{
return "0 value";
}
return myValue.ToString();
}
Then the label in the code-in-front will be something like:
<asp:Label ID="Label18" Text='<%# ProcessMyDataItem(Eval("item")) %>' runat="server"></asp:Label>
Sorry, haven’t tested this code so can’t guarantee I got the syntax of “<%# ProcessMyDataItem(Eval("item")) %>” entirely correct.
Method 2
I’m using this for string values:
<%#(String.IsNullOrEmpty(Eval("Data").ToString()) ? "0" : Eval("Data"))%>
You can also use following for nullable values:
<%#(Eval("Data") == null ? "0" : Eval("Data"))%>
Also if you’re using .net 4.5 and above I suggest you use strongly typed data binding:
<asp:Repeater runat="server" DataSourceID="odsUsers" ItemType="Entity.User">
<ItemTemplate>
<%# Item.Title %>
</ItemTemplate>
</asp:Repeater>
Method 3
I use the following for VB.Net:
<%# If(Eval("item").ToString() Is DBNull.Value, "0 value", Eval("item")) %>
Method 4
It should work as well
Eval("item") == null?"0": Eval("item");
Method 5
Moreover, you can use (x = Eval(“item”) ?? 0) in this case.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
Method 6
I don’t know ASP.NET very well, but can you use the ternary operator?
http://en.wikipedia.org/wiki/Ternary_operation
Something like:
(x=Eval(“item”)) == Null ? 0 : x
Method 7
try this code it might be useful –
<%# ((DataBinder.Eval(Container.DataItem,"ImageFilename").ToString()=="") ? "" :"<a href="+DataBinder.Eval(Container.DataItem, " rel="nofollow noreferrer noopener"link")+"><img src='/Images/Products/"+DataBinder.Eval(Container.DataItem, "ImageFilename")+"' border='0' /></a>")%>
Method 8
Used a modified version of Jason’s answer:
public string ProcessMyDataItem(object myValue)
{
if (myValue.ToString().Length < 1)
{
return "0 value";
}
return myValue.ToString();
}
Method 9
Try replacing <%# Eval("item") %> with <%# If(Eval("item"), "0 value") %> (or <%# Eval("item") ?? "0 value" %>, when using C#).
Method 10
Use IIF.
<asp:Label ID="Label18" Text='<%# IIF(Eval("item") Is DBNull.Value,"0", Eval("item") %>'
runat="server"></asp:Label>
Method 11
I have tried this code and it works well for both null and empty situations :
'<%# (Eval("item")=="" || Eval("item")==null) ? "0" : Eval("item")%>'
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0