I am making an error handelder, it will activate when i type in an invalid time or date format like 12:456 and 55-32-1986. Then the program should change the cell value back to the prev value.
I am using .NET 4.5 and this is a winforms application
The code:
dataGridView2.DataError += dataGridView2_DataError;
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;
}
if ((anError.Exception) is FormatException)
{
if (dataGridView2.CurrentCell == dataGridView2.CurrentRow.Cells[3])
{
MessageBox.Show("Please enter a valid time value" + prevTime);
dataGridView2.CurrentCell.Value = prevTime;
dataGridView2.EndEdit();
}
if (dataGridView2.CurrentCell == dataGridView2.CurrentRow.Cells[2])
{
MessageBox.Show("Please enter a valid date");
dataGridView2.CurrentCell.Value = prevDate;
dataGridView2.EndEdit();
}
}
//cell types
d.Tables.Add(booking);
booking.Columns.Add("nr.", typeof(int));
booking.Columns.Add("Name", typeof(string));
booking.Columns.Add("Date", typeof(DateTime));
booking.Columns.Add("Time", typeof(DateTime));
//Datasource
dataGridView2.DataSource = booking;
}
prevDate- and TimeValue are declared at datagrid_onBeginEdit so that i have the values.
I have the prev values. The code runs from start to end. But from row 2 and afterwards, it wont change the value of the cells programmatically. I can only do it manualy, and when the code cant change the value, then the error messagebox keeps on appearing. The datagridview is not read only.
Cells: nr. / Name / Date / Time
Any help will be appreciated, thanks in advance.
EDIT: I added the full code of the event handeler
PS. If i am unclear somewhere, or if you need more information then just tell whats needed.
DataGridView? If so, which one? - Evan L