vote up 5 vote down star
1

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.

flag

Thanks for the formatting fix, Nick. I now see how to do that. – Randy Eppinger Feb 21 at 17:22

3 Answers

vote up 9 vote down check

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)

link|flag
2  
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 Feb 17 at 17:03
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 Feb 17 at 17:15
1  
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 Feb 17 at 17:26
1  
@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 Feb 17 at 17:28
@Ruben, you're right, it should be a hash digit placeholder, e.g. {0:#,##0;;#} – Joe Feb 17 at 18:28
show 1 more comment
vote up 0 vote down

Use a custom method.

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

<%# MyFormat(Convert.ToDouble(Eval("MSDWhole"))) %>
link|flag
vote up 0 vote down

Try to call a function while binding like this

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

and inside the function make the formatting you want

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.