Using '<%# Eval(“item”) %>'; Handling Null Value and showing 0 against

我怕爱的太早我们不能终老 提交于 2019-11-26 22:34:31

问题


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?


回答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.




回答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>



回答3:


I use the following for VB.Net:

<%# If(Eval("item").ToString() Is DBNull.Value, "0 value", Eval("item")) %>



回答4:


It should work as well

Eval("item") == null?"0": Eval("item");



回答5:


Moreover, you can use (x = Eval("item") ?? 0) in this case.

http://msdn.microsoft.com/en-us/library/ms173224.aspx




回答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




回答7:


try this code it might be useful -

<%# ((DataBinder.Eval(Container.DataItem,"ImageFilename").ToString()=="") ? "" :"<a
 href="+DataBinder.Eval(Container.DataItem, "link")+"><img
 src='/Images/Products/"+DataBinder.Eval(Container.DataItem,
 "ImageFilename")+"' border='0' /></a>")%>



回答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();
}



回答9:


Try replacing <%# Eval("item") %> with <%# If(Eval("item"), "0 value") %> (or <%# Eval("item") ?? "0 value" %>, when using C#).




回答10:


Use IIF.

<asp:Label ID="Label18" Text='<%# IIF(Eval("item") Is DBNull.Value,"0", Eval("item") %>' 
runat="server"></asp:Label>



回答11:


I have tried this code and it works well for both null and empty situations :

'<%# (Eval("item")=="" || Eval("item")==null) ? "0" : Eval("item")%>'


来源:https://stackoverflow.com/questions/1979806/using-evalitem-handling-null-value-and-showing-0-against

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!