在 DataGridView 中使用自定义格式化程序
所以,也许这是一个糟糕的设计;我不知道。但是假设我有一个 DataTable,其中有一列保存 int 值;这些值实际上意味着代表我项目中的某些enum
类型。
我想要做的是将 DataGridView
绑定到此表,并让列显示 enum
的名称,而不是整数值“0”或“1” “或者其他什么。
我考虑的一个选择是完成整个标准化工作:在 DataSet
中添加一个表,其中包含 enum
名称,并以 enum
为键值,并让我的第一个表保存对此表的引用。
但这是一个特定于enum
的想法。我想知道,一般来说,我是否可以为给定类型编写自己的 IFormatProvider
和 ICustomFormatter
实现*,并使用该格式化程序来控制值在DataGridView
控件的给定列(或者实际上在任何 控件中)。
*这就是我怀疑的方式,如果我所要求的事情是可能的的话。我并没有真正下定决心要使用这些接口。
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.
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.
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.
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).
*This is just how I suspect it would be done, if what I'm asking is possible at all. I'm not really dead-set on using these interfaces at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确实可以实现自定义
ICustomFormatter
,但由于DataGridView
部分存在一些问题,您需要实际告诉它如何应用您的格式化程序。首先将
column.DefaultCellStyle.FormatProvider
设置为自定义格式设置类的实例。然后,处理CellFormatting
事件:格式化程序类将如下所示:
You can indeed implement a custom
ICustomFormatter
, but due to some brokenness on the part of theDataGridView
, you need to actually tell it how to apply your formatter.First set
column.DefaultCellStyle.FormatProvider
to an instance of your custom formatting class. Then, handle theCellFormatting
event:The formatter class would look something like this: