I’ve seen these questions but both involve methods that aren’t available in the CellStyle Format value. I only want to show the hours and minutes portion (16:05); not the seconds as well (16:05:13). I tried forcing the seconds value to zero but still got something like 16:05:00. Short of using a kludge like providing a string or a DateTime (and only showing the hour/minutes part) is there any way I can get the formatting to do what I want.
I’ve seen these questions but both involve methods that aren’t available in the CellStyle
Share
I just discovered this myself. Unfortunately, the solution is pretty involved. The good news is that it works.
Firstly, you need an
ICustomFormatterimplementation that deals withTimeSpanvalues. The .NET framework does not include such a type out-of-the-box; I am guessing this is because Microsoft didn’t want to have to deal with the ambiguity involved in formatting aTimeSpan(e.g., does “hh” mean total hours or only the hour component?) and the ensuing onslaught of support issues that would arise when these ambiguities confused developers.That’s OK — just implement your own. Below is a sample class I wrote that uses basically the same custom format strings as
DateTime(those that were applicable, anyway)*:We’re not finished yet. With this type in place, you are equipped to assign a custom formatter to the column in your
DataGridViewthat you want to use for displaying yourTimeSpanvalues.Let’s say that column is called “Time”; then you would do this:
So now you’re set up, right?
Well, for some odd reason, you’re still not 100% of the way there. Why custom formatting can’t kick in at this point, I honestly couldn’t tell you. But we’re almost done. The one final step is to handle the
CellFormattingevent to get this new functionality we’ve written to actually take effect:At last, we’re finished. Setting the
DefaultCellStyle.Formatproperty of theDataGridViewColumnyou want formatted according to your custom rules should now work as expected.*So, “h”/”hh” for hours, “m”/”mm” for minutes. etc.