![](/img/trans.png)
[英]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.