问题描述
所以,也许这是一个糟糕的设计;我不知道.但是假设我有一个 DataTable
,其中有一列包含 int
值;这些值实际上是为了表示我的项目中的一些 enum
类型.
So, maybe this is a bad design; I don't know. But say I have a DataTable
with a column that holds int
values; these values are in fact meant to represent some enum
type that I have in my project.
我想做的是将 DataGridView
绑定到这个表,并让列显示 enum
的名称而不是整数值0"或1"或其他什么.
What I'd like to do is have a DataGridView
bound to this table and have the column display the name of the enum
rather than the integer value "0" or "1" or whatever.
我考虑的一个选择是做整个规范化的事情:在 DataSet
中添加一个表,其中包含 enum
名称,键入 enum
值,并让我的第一个表保存对这个表的引用.
One option I considered was to do the whole normalization thing: add a table in the DataSet
with the enum
names in it, keyed on the enum
values, and have my first table hold a reference to this table.
但这是一个 enum
特定的想法.我想知道,一般来说,我是否可以为给定类型编写自己的 IFormatProvider
和 ICustomFormatter
实现*,并使用该格式化程序来控制值的显示方式DataGridView
控件的给定列(或者实际上在 任何 控件中,就此而言).
But this is an enum
-specific idea. I would like to know if, in general, I can write my own IFormatProvider
and ICustomFormatter
implementation* for a given type and use that formatter to control how values are displayed in a given column of a DataGridView
control (or really in any control, for that matter).
推荐答案
你确实可以实现一个自定义的 ICustomFormatter
,但是由于 DataGridView
部分的一些延迟,您需要实际告诉它如何应用您的格式化程序.
You can indeed implement a custom ICustomFormatter
, but due to some retardedness on the part of the DataGridView
, you need to actually tell it how to apply your formatter.
首先将 column.DefaultCellStyle.FormatProvider
设置为自定义格式设置类的实例.然后,处理 CellFormatting
事件:
First set column.DefaultCellStyle.FormatProvider
to an instance of your custom formatting class. Then, handle the CellFormatting
event:
void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
if (e.CellStyle.FormatProvider is ICustomFormatter) {
e.Value = (e.CellStyle.FormatProvider.GetFormat(typeof(ICustomFormatter)) as ICustomFormatter).Format(e.CellStyle.Format, e.Value, e.CellStyle.FormatProvider);
e.FormattingApplied = true;
}
}
格式化程序类看起来像这样:
The formatter class would look something like this:
public class MyEnumFormatter : IFormatProvider, ICustomFormatter {
public object GetFormat(Type formatType) {
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider) {
return ((NameOfEnumType)Convert.ToInt32(arg)).ToString();
}
}
这篇关于在 DataGridView 中使用自定义格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!