views:

366

answers:

4

I am using a DataBinder.Eval expression in an ASP.NET Datagrid, but I think this question applies to String formatting in .NET in general. The customer has requested that if the value of a string 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 {0:N0} formatting expression so that I can eliminate the IIf statement, but can't find anything that works.

+9  A: 

You need to use the section separator, like this:

<%# 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 the 0 section. (Read the documentation)

SLaks
It's a good day. I learned something and it's not even 10 a.m. yet! I wish I could upvote twice.
No Refunds No Returns
Almost right, but N0 is a standard format and you need a custom format, e.g. "{0:#,##0;;}". You don't need to put a space in the third section.
Joe
Caution, this won't work as you think it would: for MSDWhole != 0, you'd get "N<value>". N0 is not supported with group separators. Use "{0:#,0;; }"
Ruben
@Joe: you *do* need either a space or `''` for the third group, as an empty group is ignored. {0:+A;-A;} returns +A for 0. With `''` no Trim is needed.
Ruben
@Ruben, you're right, it should be a hash digit placeholder, e.g. {0:#,##0;;#}
Joe
Thanks all for the discussion. {0:N0;; } works. @Joe, your last comment entry also works. BTW, this did not work if the number being formatted was a string containing a number. It works for 0, but not "0" .
Randy Eppinger
`It DoubleEmitsBlankWhenZeroInStringFormat = () => string.Format("{0:$#,0;$#,0;#}", 0d).ShouldEqual(string.Empty);` - the hash in the last position works
Dave
A: 

Use a custom method.

public static string MyFormat(double value) {       
    return value == 0 ? "" : value.ToString("0");
}

<%# MyFormat(Convert.ToDouble(Eval("MSDWhole"))) %>
Sam
A: 

Try to call a function while binding like this

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

and inside the function make the formatting you want

Amgad Fahmi
A: 

Given the accepted answer:

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

The a space is placed in the the 3rd position, however placing a # in the third position will eliminate the need to call Trim().

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;;#}") %>
Dave
Dave, I tried this idea and it worked great! Dropping the trim is definitely an improvement. Thanks!
Randy Eppinger