Check if string has valid DateTime format

  • Thread starter Magnus.Moraberg
  • Start date
M

Magnus.Moraberg

Hi,

I have the following event which checks if a cell in a dgv contains a
date and if so, checks if it is formatted correctly. I don't think its
good practice for be to try this by catching an exception. Is there a
better way? Notice also my use of a dummy dateTime object. Also, does
the DateTime object contain any information about how it should be
formatted? For example -

"Format Error: DateTime cell incorrectly formatted. Expected format: "
+ DateTime.ExpectedFormat;

Thanks,

Barry.

private void DataGridView_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
DataGridView dataGridView = ((DataGridView)sender);
DataGridViewCell dataGridViewCell =
dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];

// if formatting a DateTime cell
if (dataGridViewCell.ValueType == typeof(DateTime))
{
try
{
DateTime dateTime = (DateTime)((new
DateTimeConverter()).ConvertFromString((string)e.FormattedValue));
}
catch (FormatException formatException)
{
dataGridView.Rows[e.RowIndex].ErrorText = "Format
Error: DateTime cell incorrectly formatted.";
e.Cancel = true;
}
}
}
 
A

Alberto Poblacion

[...] I don't think its
good practice for be to try this by catching an exception. Is there a
better way?

You can use DateTime.TryParse (or TryParseExact), which will return
false if the string cannot be parsed as a DateTime, without throwing an
exception.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top