代码之家  ›  专栏  ›  技术社区  ›  Blorgbeard

我是否可以在属性上使用属性来告诉DataGridView如何格式化列?

  •  8
  • Blorgbeard  · 技术社区  · 17 年前

    从 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 ,还是我必须在创建列后处理它们?

    2 回复  |  直到 9 年前
        1
  •  5
  •   Blorgbeard    17 年前

    像这样。

    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"); }
      }
    }
    
        2
  •  5
  •   Marc Gravell    17 年前

    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);
        }
    }
    
    推荐文章