Can I format NULL values in string.Format?

那年仲夏 提交于 2019-11-30 10:44:26

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();
    }
}

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);

Is this what you want?

string test;

test ?? "NULL"

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(...);
Black White

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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!