C# DataGridView:使用CellParsing获得可为null的<;时间跨度>;
我正在尝试为DataGridView实现自定义解析。它应该将输入的值转换为时间跨度?(可为空) 我的代码如下: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
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
,因为我想对输入的值进行自定义解析。我也有同样的问题,您找到解决方案了吗?