将hhmm DataGridView单元格值转换为TimeSpan字段

问题描述

|| 我想在DataGridView列中显示为hhmm的TimeSpan字段。并允许用户以这种格式对其进行编辑。据我了解,我需要为CellFormatting,CellParsing和CellValidating事件添加一些逻辑。因此,我想我必须检查列名,并为需要此名称的人处理。 但是,出于代码重用的目的,我还能如何更好地解决此问题呢?我可以制作一个自定义DataGridViewColumn类,在其中放置此逻辑吗?如何实现?我看不到DataGridViewColumn类存在的任何事件,因此不确定在这里做什么。     

解决方法

我将看一下这种类型的
DataGridViewColumn.CellTemplate
属性:
public abstract class DataGridViewCell : DataGridViewElement,ICloneable,IDisposable
具有以下有趣的属性:
Value: object
ValueType: Type
ValueTypeConverter: TypeConverter
从那里,我来看看
TypeConverter
类。 希望这会有所帮助,这就是我在大约2分钟的ILSpy中可以收集到的信息。     ,也许对您来说太迟了,但是我想这会帮助别人。昨天我几乎遇到了同样的问题。 我通过为TimeSpan成员创建class-wrapper来解决此问题,在该成员中我覆盖了ToString方法(以便以首选格式显示时间)并创建了Parse(String)方法,当用户完成单元格编辑时会自动调用该方法。最后,为了捕获可能在Parse方法中生成的异常,请为DataGridView的DataError事件创建处理程序。 例:
class TimeSpanDecorator
{
    protected TimeSpan timeSpan;
    public TimeSpanDecorator(TimeSpan ts)
    {
        timeSpan = ts;
    }
    public override string ToString() // return required TimeSpan view
    {
        return timeSpan.Hours + \":\" + timeSpan.Minutes;
    }
    public static TimeSpanDecorator Parse(String value) // parse entered value in any way you want
    {
        String[] parts = value.Split(\':\');
        if (parts.Length != 2)
            throw new ArgumentException(\"Wrong format\");
        int hours = Int32.Parse(parts[0]);
        int minutes = Int32.Parse(parts[1]);
        TimeSpanDecorator result = new TimeSpanDecorator(new TimeSpan(hours,minutes,0));
        if (result.timeSpan.Ticks < 0)
            throw new ArgumentException(\"You should provide positive time value\");
        return result;
    }
    //other members
}

internal partial class MainForm : Form
{
    (...)
    private void dataGridView_DataError(object sender,DataGridViewDataErrorEventArgs e)
    {
        MessageBox.Show(\"Error occured: \" + e.Exception.Message,\"Warning!\"); // showing generated argument exception
        e.ThrowException = false; // telling form that we have processed the error
    }
}
希望这会帮助任何人。