0
I’m creating a form where the user will input data through a DataGridView
, one of the columns of this DataGridView
is the type DataGridViewTextBoxColumn
and it will receive a date, I would like to validate that date after the user has typed it. Through of that answer at Soen, I discovered the event EditingControlShowing
, then 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 event KeyPress
works perfectly, accepting only numbers, bar and control characters, however the event Validating
does not work as expected, as soon as the error message appears and the user clicks OK, the invalid date goes back to the cell and the focus goes to another row or column, depending on which key was pressed (ENTER or TAB).
Does anyone have any idea how to solve this problem or has another suggestion on how to do this validation?
Note: I tried to reproduce this case in a new project and the same problem was presented.
Just as a suggestion try using the
dataGridView1_CellValidating
. https://msdn.microsoft.com/en-us/library/7ehy30d4(v=vs.85). aspx– Jothaz
@Jay, this link helped, I combined the
KeyPress
ofDataGridViewTextBoxColumn
with theCellValidating
ofDataGridView
, can elaborate as an answer. I just found it strange that theValidating
, but finally, solved the problem.– mateusalxd