I'm making a datagridview with four columns. The last column's type is DateTime in Hours and minutes (HH:mm).
DataTable.Columns.Add("Time", typeof(DateTime)); //fourth column
dataGridView2.Columns[3].DefaultCellStyle.Format = "HH:mm";
When i put in a valid HH:mm(12:37) format it works just fine, but it gives me an error message if the format is invalid (12:374).
The string wasn't regigniced as a valid DateTime --> System.FormatExeption
It tells me to handle the "DataError-exeption / FormatExeption" to change what happens when the error occurs, but how do i do that?
I want it to go back to the value it was before the error occurs.
Any help will be appreciated. thanks in advance.
PS. If i'm unclear somewhere, or if you need more information then just explain what's needed.
EDIT: I am editing the time value directly from the dataGridView.
Handle the event DataGridView.DataError so that you can proper manage the situation and show the correct messages to the user.
This example of event-handler below is taken from MSDN:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
MessageBox.Show("Error happened " + anError.Context.ToString());
if (anError.Context == DataGridViewDataErrorContexts.Commit)
{
MessageBox.Show("Commit error");
}
if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
{
MessageBox.Show("Cell change");
}
if (anError.Context == DataGridViewDataErrorContexts.Parsing)
{
MessageBox.Show("parsing error");
}
if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
{
MessageBox.Show("leave control error");
}
if ((anError.Exception) is ConstraintException)
{
DataGridView view = (DataGridView)sender;
view.Rows[anError.RowIndex].ErrorText = "an error";
view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
anError.ThrowException = false;
}
}
And add it to your DataGridView instance:
dataGridView2.DataError += dataGridView2_DataError;
You can get more information about the event and input parameters expected from this resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With