I'm creating a form where the user will enter data through a DataGridView
, one of the columns of that DataGridView
is of type DataGridViewTextBoxColumn
and it will receive a date, I would like to validate that date after the user enters it. Through this answer in SOen, I discovered the EditingControlShowing
event, so I did the following:
private void grdFeriados_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
var controle = e.Control as DataGridViewTextBoxEditingControl;
// a coluna de index 0 é a coluna que receberá a data
if (controle != null && ((DataGridView)sender).CurrentCell.ColumnIndex == 0)
{
controle.KeyPress -= new KeyPressEventHandler(controle_KeyPress);
controle.Validating -= new CancelEventHandler(controle_Validating);
controle.KeyPress += new KeyPressEventHandler(controle_KeyPress);
controle.Validating += new CancelEventHandler(controle_Validating);
}
}
private void controle_KeyPress(Object sender, KeyPressEventArgs e)
{
if (!Char.IsNumber(e.KeyChar) && !e.KeyChar.Equals('/') && !Char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void controle_Validating(object sender, CancelEventArgs e)
{
var controle = ((DataGridViewTextBoxEditingControl)sender);
// ValidateUtils é uma classe estática utilizada para validação
if (!string.IsNullOrEmpty(controle.Text) && !ValidateUtils.IsDate(controle.Text))
{
controle.Clear();
e.Cancel = true;
MessageBox.Show("Data inválida.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The KeyPress
event works perfectly, accepting only numbers, the bar and control characters, but the Validating
event does not work as expected, as soon as the error message appears and the user clicks OK, the date ( ENTER or TAB ).