使用自定义属性控制 DataGridView 列的外观
当自动生成列时DataGridView
,对一些属性有内置支持,包括ReadOnly
, DisplayName
and Browsable
属性。例如,如果您使用Browsable(false)
它不会作为列添加到DataGridView
.
But for Format
,没有这样的内置支持。您可以创建一个自定义DisplayFormat
属性并编写一些代码来使用它DataGridView
自动生成列后。
例如,假设您有一个这样的类:
using System;
using System.ComponentModel;
public class Product
{
[DisplayName("Code")]
[Description("Unique code of the product")]
public int Id { get; set; }
[DisplayName("Product Name")]
[Description("Name of the product")]
public string Name { get; set; }
[DisplayName("Unit Price")]
[Description("Unit price of the product")]
[DisplayFormat("C2")]
public double Price { get; set; }
}
结果,我们将会有一个DataGridView
就像截图一样,可以看到我们使用了Description
属性作为列的工具提示文本,我们也使用DisplayFormat
以货币格式显示价格:
首先我们应该创建格式的自定义属性,DisplayFormat
:
using System;
using System.ComponentModel;
public class DisplayFormatAttribute : Attribute
{
public DisplayFormatAttribute(string format)
{
Format = format;
}
public string Format { get; set; }
}
然后加载数据并自动生成列,例如:
var list = new List<Product>() {
new Product(){ Id=1, Name="Product 1", Price= 321.1234},
new Product(){ Id=2, Name="Product 2", Price= 987.5678},
};
this.dataGridView1.DataSource = list;
然后,为了利用属性,您可以编写不依赖于模型类型的代码:
var type = ListBindingHelper.GetListItemType(dataGridView1.DataSource);
var properties = TypeDescriptor.GetProperties(type);
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
var p = properties[column.DataPropertyName];
if (p != null)
{
var format = (DisplayFormatAttribute)p.Attributes[typeof(DisplayFormatAttribute)];
column.ToolTipText = p.Description;
column.DefaultCellStyle.Format = format == null ? null : format.Format;
}
}
您可以简单地将上面的代码封装在类似的方法中void SetupColumn(DataGridView dgv)
或者如果你有一个派生的DataGridView
,您可以创建一个DataBind(object data)
方法并在该方法中分配data
to DataSource
然后使用上面的代码作为方法体的其余部分。
Note
我还在你的问题下的评论中读到你已经告诉过'...每个字段都有点多。' 如果出于某种原因你不喜欢属性方法,你可以简单地坚持使用这样的 for 循环:
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
if (c.ValueType == typeof(double))
{
c.DefaultCellStyle.Format = "C2";
c.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
}
Windows 窗体中的 DataAnnotations 属性
要了解如何在 Windows 窗体中将数据注释属性用于 DataGridView 和验证,请查看以下文章:
- Windows 窗体中 DataGridView 的 DataAnnotations 属性
- Windows 窗体的 DataAnnotations 验证属性