Using .NET string formatting, how do I format a string to display empty (empty string) for zero (0)?

I am using the DataBinder.Eval expression in an ASP.NET Datagrid, but I think this question relates to formatting strings in .NET in general. The client requested that if the string value is 0, it should not be displayed. I have the following hack to accomplish this:

<%# IIf(DataBinder.Eval(Container.DataItem, "MSDWhole").Trim = "0", "", DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0}")) %> 

I would like to change the formatting expression {0:N0} so that I can exclude the IIf statement, but cannot find anything that works.

+6
formatting string.format string-formatting
source share
4 answers

You need to use a partition delimiter for example:

 <%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %> 

Note that only the negative section can be empty, so I need to put a space in section 0 . (Read the documentation )

+10
source share

Given the accepted answer:

 <%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %> 

The space is placed in the third position, but placing # in the third position eliminates the need to call Trim() .

 <%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;;#}") %> 
+3
source share

Use your own method.

 public static string MyFormat(double value) { return value == 0 ? "" : value.ToString("0"); } <%# MyFormat(Convert.ToDouble(Eval("MSDWhole"))) %> 
0
source share

Try calling the function when binding as

 <%# MyFunction( DataBinder.Eval(Container.DataItem, "MSDWhole") ) %> 

and inside the function do the necessary formatting

0
source share

All Articles