[英]Is there an Attribute I can use in my class to tell DataGridView not to create a column for it when bound to a List<MyClass>
[英]Is there an Attribute I can use on a property to tell DataGridView how to format the column?
关于这个问题的一点点,如果我有这个课:
private class MyClass {
[DisplayName("Foo/Bar")]
public string FooBar { get; private set; }
public decimal Baz { get; private set; }
}
我想在DataGridView
显示List<MyClass>
(带有自动生成的列),将Baz列显示格式化为货币的最简单方法是什么?
是否有一个我可以使用的属性,比如我正在使用DisplayName
,或者在创建列后我是否必须弄乱它们?
我知道它不完美但你可以添加另一个名为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"); }
}
}
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.