2

I'm trying to implement a custom parsing for a DataGridView. It's supposed to convert the entered value to a TimeSpan? (Nullable<TimeSpan>).

My code is as follows:

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 is an extension method which returns true if the supplied string can be converted to a TimeSpan.

ToTimeSpan is another extension which performs my custom parsing.

So far, so good, the parsing works perfectly for entered numbers.

The problem is with entering invalid characters (' ' (single whitespace), 'x', ...), which sets e.Value to null. Then I always get a DataGridView error popup.

If I enter nothing (type something and delete it all and then leave the cell), it doesn't display said error.

What am I doing wrong and how can I fix this?

4

0 回答 0