Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DataGridView:使用CellParsing获得可为null的<;时间跨度>;_C#_Winforms_Parsing_Datagridview_Timespan - Fatal编程技术网

C# DataGridView:使用CellParsing获得可为null的<;时间跨度>;

C# DataGridView:使用CellParsing获得可为null的<;时间跨度>;,c#,winforms,parsing,datagridview,timespan,C#,Winforms,Parsing,Datagridview,Timespan,我正在尝试为DataGridView实现自定义解析。它应该将输入的值转换为时间跨度?(可为空) 我的代码如下: private void dataGridViewWeek_CellParsing(object sender, DataGridViewCellParsingEventArgs e) { if((e.Value is string) && (e.DesiredType == typeof(TimeSpan?))) { string ls

我正在尝试为DataGridView实现自定义解析。它应该将输入的值转换为时间跨度?(可为空)

我的代码如下:

private void dataGridViewWeek_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
    if((e.Value is string) && (e.DesiredType == typeof(TimeSpan?)))
    {
        string lsValue = ((string)e.Value).Trim();

        if(!lsValue.IsTimeSpan()) e.Value = null;
        else e.Value = lsValue.ToTimeSpan();

        e.ParsingApplied = true;
    }
}
IsTimeSpan是一种扩展方法,如果提供的字符串可以转换为TimeSpan,则返回true

ToTimeSpan是执行自定义解析的另一个扩展

到目前为止,很好,解析对于输入的数字非常有效

问题在于输入无效字符(“”(单空格)、“x”、…),这会将e.Value设置为null。然后我总是得到一个DataGridView错误弹出窗口

如果我不输入任何内容(键入某个内容并将其全部删除,然后离开单元格),则不会显示所述错误


我做错了什么?如何解决这个问题?

更改
e.Value=null
e.Value=新的时间跨度?()也没有帮助。如果自定义
IsTimeSpan
检查失败,则您必须向我们显示该代码。有什么原因不能只使用
TimeSpan.TryParse
TimeSpan.TryParseExact
来代替吗?@Matt Johnson它在
IsTimeSpan
上没有失败,该方法完全按照预期工作,双重-不,三次检查。我没有使用
TimeSpan.TryParse
TimeSpan.TryParseExact
,因为我想对输入的值进行自定义解析。我也有同样的问题,您找到解决方案了吗?