来自this question的一点,如果我有这个课程:
private class MyClass {
[DisplayName("Foo/Bar")]
public string FooBar { get; private set; }
public decimal Baz { get; private set; }
}
我想在List<MyClass>
(自动生成的列)中显示DataGridView
,将Baz列显示格式化为货币的最简单方法是什么?
是否有我可以使用的属性,例如我正在使用DisplayName
,或者在创建列后我是否需要使用这些列?
答案 0 :(得分:5)
我知道它不完美,但你可以添加另一个名为CurrencyBaz的属性,它基本上会返回格式化的Baz,然后将其绑定到网格而不是真正的Baz。
这样的事情。
private class MyClass {
[DisplayName("Foo/Bar")]
public string FooBar { get; private set; }
[Browsable(False)]
public decimal Baz { get; private set; }
[DisplayName("Baz")]
public CurrencyBaz
{
get { return string.Format(Baz, "C2"); }
}
}
答案 1 :(得分:5)
TypeConverterAttribute
- 类似于:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form { Controls = {
new DataGridView {
Dock = DockStyle.Fill,
DataSource = new List<MyClass> {
new MyClass { FooBar = "abc", Baz = 123.45M},
new MyClass { FooBar = "def", Baz = 678.90M}
}
}
}});
}
}
class MyClass
{
[DisplayName("Foo/Bar")]
public string FooBar { get; set; }
[TypeConverter(typeof(CurrencyConverter))]
public decimal Baz { get; set; }
}
class CurrencyConverter : DecimalConverter
{
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
string s = value as string;
if (s != null) return decimal.Parse(s, NumberStyles.Currency, culture);
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return ((decimal)value).ToString("C2", culture);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}