将 hhmm DataGridView 单元格值转换为 TimeSpan 字段
我想将 DataGridView 列中的 TimeSpan 字段显示为 hhmm。并允许用户以这种格式进行编辑。据我了解,我需要向 CellFormatting、CellParsing 和 CellValidating 事件添加一些逻辑。所以我想我必须检查列名,并为那些需要它的人处理它。
但是为了代码重用的目的,我还能如何更好地解决这个问题呢?我可以创建一个自定义的 DataGridViewColumn 类来放置此逻辑吗?如何实现这一目标?我看不到 DataGridViewColumn 类存在的任何事件,因此不太确定在这里要做什么。
I want to display a TimeSpan field in a DataGridView column as hhmm. And allow the user to edit it in this format. As far as I understand, I need to add some logic to CellFormatting, CellParsing, and CellValidating events. So I guess I must check the column name, and handle it for those that require this.
But how else can I better solve this for the purpose of code reuse? Can I make a custom DataGridViewColumn class where I can put this logic? How would that be achieved? I can't see any events existing for the DataGridViewColumn class, so not really sure what to do here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将查看
DataGridViewColumn.CellTemplate
属性,该属性属于以下类型:它具有这些有趣的属性:
从那里,我将查看
TypeConverter
类。希望这会有所帮助,这就是我在浏览 ILSpy 大约 2 分钟内可以收集到的内容。
I would look at
DataGridViewColumn.CellTemplate
property, which is of this type:which has these interesting properties:
from there, I would look at the
TypeConverter
class.Hope this helps, that's what I could gather in about 2 minutes of looking through ILSpy.
也许对你来说为时已晚,但我想这会对其他人有所帮助。我昨天遇到了几乎同样的问题。
我通过为 TimeSpan 成员创建类包装器来解决这个问题,其中我覆盖了 ToString 方法(以便以首选格式显示时间)并创建了 Parse(String) 方法,当用户完成单元格编辑时会自动调用该方法。最后,为了捕获可能在 Parse 方法中生成的异常,请为 DataGridView 的 DataError 事件创建处理程序。
示例:
希望这对任何人都有帮助。
Maybe it is too late for you, but I guess it would help others. I had almost the same issue yesterday.
I solved it by creating class-wrapper to my TimeSpan member, where I overrode ToString method (in order to display time in preferred format) and created Parse(String) method, which is called automatically when user is finishing cell editing. Finally, in order to catch exceptions, which may be generated in Parse method, create handler for DataGridView's DataError event.
Example:
Hope this will help anyone.