6

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.

1
  • Thanks for the formatting fix, Nick. I now see how to do that. Commented Feb 21, 2010 at 17:22

4 Answers 4

10

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)

Sign up to request clarification or add additional context in comments.

7 Comments

It's a good day. I learned something and it's not even 10 a.m. yet! I wish I could upvote twice.
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.
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;; }"
@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, you're right, it should be a hash digit placeholder, e.g. {0:#,##0;;#}
|
3

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;;#}") %>

1 Comment

Dave, I tried this idea and it worked great! Dropping the trim is definitely an improvement. Thanks!
0

Use a custom method.

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

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

Comments

0

Try to call a function while binding like this

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

and inside the function make the formatting you want

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.