Can I format NULL values in string.Format?

前端 未结 5 1930
粉色の甜心
粉色の甜心 2021-01-01 08:55

I was wondering if there\'s a syntax for formatting NULL values in string.Format, such as what Excel uses

For example, using Excel I could specify a format value of

相关标签:
5条回答
  • 2021-01-01 09:16

    I don't think there's anything in String.Format that will let you specify a particular format for null strings. A workaround is to use the null-coalescing operator, like this:

    const string DefaultValue = "(null)";
    
    string s = null;
    string formatted = String.Format("{0}", s ?? DefaultValue);
    
    0 讨论(0)
  • 2021-01-01 09:19

    You can define a custom formatter that returns "NULL" if the value is null and otherwise the default formatted string, e.g.:

    foreach (var value in new[] { 123456.78m, -123456.78m, 0m, (decimal?)null })
    {
        string result = string.Format(
            new NullFormat(), "${0:#,000.00;(#,000.00);ZERO}", value);
        Console.WriteLine(result);
    }
    

    Output:

    $123.456,78
    $(123.456,78)
    $ZERO
    $NULL
    

    Custom Formatter:

    public class NullFormat : IFormatProvider, ICustomFormatter
    {
        public object GetFormat(Type service)
        {
            if (service == typeof(ICustomFormatter))
            {
                return this;
            }
            else
            {
                return null;
            }
        }
    
        public string Format(string format, object arg, IFormatProvider provider)
        {
            if (arg == null)
            {
                return "NULL";
            }
            IFormattable formattable = arg as IFormattable;
            if (formattable != null)
            {
                return formattable.ToString(format, provider);
            }
            return arg.ToString();
        }
    }
    
    0 讨论(0)
  • 2021-01-01 09:30

    You could use an extension method:

     public static string ToDataString(this string prm)
       {
           if (prm == null)
           {
               return "NULL";
           }
           else
           {
               return "'" + prm.Replace("'", "''") + "'";
           }
       }
    

    Then in your code you can do:

    string Field1="Val";
    string Field2=null;
    
    string s = string.Format("Set Value:{0}, NullValue={1}",Field1.ToDataString(), Field2.ToDataString());
    
    0 讨论(0)
  • 2021-01-01 09:31

    It looks like String.Format for .NET acts the same way as Excel, i.e., you can use ; separator for positive, negative, and 0 values, but not NULL: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator.

    You will probably just have to handle the null value manually:

    if (myval == null)
        // handle
    else
        return String.Format(...);
    
    0 讨论(0)
  • 2021-01-01 09:34

    Is this what you want?

    string test;
    

    test ?? "NULL"

    0 讨论(0)
提交回复
热议问题