Situation:
I'm writing a Winforms app using C# in VS2013 with .NET4.0.
Some cells in a datagridview need to be validated as correctly formatted UK currency values. The dgv cell format is set to currency with two decimal places. For validation I'm using the following code:
decimal convertedCurrency;
if (decimal.TryParse(dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString(), NumberStyles.Currency, null, out convertedCurrency))
{
if (convertedCurrency > columnDetails.MaxValue || convertedCurrency < 0)
{
this.ReportError(dataGrid, e, dataGrid.Columns[e.ColumnIndex].HeaderText + " must be between £0 and £" + columnDetails.MaxValue);
}
}
else
{
this.ReportError(dataGrid, e, "Incorrect format for a money value");
}
Issue:
This works prefectly except if the user inputs a value with more than two decimal places e.g. 100.001. This is deemed valid and this value is written to the database.
Question:
How can I best validate such that user input with more than two decimal places caught and handled? I could of course get into some messy string handling but is there a more ellegant way, ideally continuing to use TryParse?
See Find number of decimal places in decimal value regardless of culture to find the number of decimal places. Just verify that it's <= 2.
e.g.