开发者

.NET DataGridView: Correct way of dealing with parsing errors while handling the CellParsing event?

开发者 https://www.devze.com 2022-12-20 05:44 出处:网络
I am currently developing an application for an angle measurement device (goniometer). A DataGridView component is used for configurin开发者_如何学Cg nominal values (and tolerances) for the measured a

I am currently developing an application for an angle measurement device (goniometer). A DataGridView component is used for configurin开发者_如何学Cg nominal values (and tolerances) for the measured angles. The user shall be able to enter the angles in various ways, such as 2° (for degrees) or 120' (for minutes of arc) or 7200" (for arcseconds). For this I created a parser which will convert a valid string to the angular value (a double, in degree) or fail if the string is not valid.

As I understand the correct point of time to invoke the parser is during handling of the CellParsing event. But how do I correctly handle the case when parsing has failed?

According to MSDN sample code I get the idea that I should leave the ParsingApplied property of the DataGridViewCellParsingEventArgs (which is passed to the CellParsing handler) set to false. If I do this (and leave the Value property unchanged) a FormatException is thrown by conversion attempts that are then done by the framework which raises the DataError event. Instead of a FormatException which contains a rather unspecific error message I would like to have an exception which contains information about the specific error which caused my parser implementation to fail so that I can show a specific error message in the DataError event. I assumed that I can throw a FormatException myself from within the CellParsing handler but this exception is not caught by the framework and thus does not result in raising the DataError event (in fact the outmost exception handler terminates the application).


The DataGridView data errors are a nightmare to get the hang of.
I've had to deal with this a lot recently, and in the end I just gave up and made my own implementation of DataGridViewColumn and DataGridViewCell. Doing so avoids all parsing errors, as you specifically handle it all yourself within your cell's ParseFormattedValue method.

My experience with all of this was turbulent but very worthwhile, as now I have a user interface that allows many different types of data to be input into a cell.

You can see some code I came up with to do this in a question I posted on MSDN here.
You can adapt that to match your own formatting (hopefully you can see what it's doing).

0

精彩评论

暂无评论...
验证码 换一张
取 消