I have a DataGridView that contains several columns and there are two Columns which should only allow the user to type the time , I have made it from the following way:
Event EditingControlShowing to invoke the KeyPress
method:
private void data_grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox textbox = e.Control as TextBox;
if (textbox != null)
{
textbox.KeyPress -= new KeyPressEventHandler(data_grid_KeyPress);
textbox.KeyPress += new KeyPressEventHandler(data_grid_KeyPress);
}
}
KeyPress Method:
private void data_grid_KeyPress(object sender, KeyPressEventArgs e)
{
if (data_grid.CurrentCell.ColumnIndex == 4 || data_grid.CurrentCell.ColumnIndex == 5)
{
//(char)58 pulsan :
//(char)65 pulsan A
//(char)77 pulsan M
//(char)80 pulsan P
//(char)97 pulsan a
//(char)109 pulsan m
//(char)112 pulsan p
//(char)46 pulsan .
//(char)8 pulsan Borrar
//(char)13 pulsan enter
//(char)32 pulsan espacio
//Nota: evento.Handled es false por defecto.
if (char.IsNumber(e.KeyChar) | e.KeyChar == (char)8 | e.KeyChar == (char)Keys.Escape) // Si es un numero o borrar
{
e.Handled = false; // No hacemos nada y dejamos que el sistema controle la pulsación de tecla
return;
}
if (e.KeyChar == (char)46 | e.KeyChar == (char)58) // Si es un punto o dos puntos
{
e.Handled = false; // No hacemos nada y dejamos que el sistema controle la pulsación de tecla
return;
}
if (e.KeyChar == (char)65 | e.KeyChar == (char)77 |
e.KeyChar == (char)80 | e.KeyChar == (char)97 |
e.KeyChar == (char)109 | e.KeyChar == (char)112 |
e.KeyChar == (char)32)
{
e.Handled = false; // No hacemos nada y dejamos que el sistema controle la pulsación de tecla
return;
}
else if (e.KeyChar == (char)13) // Si es un enter
{
e.Handled = true; //Interceptamos la pulsación para que no la permita.
SendKeys.Send("{TAB}"); //Pulsamos la tecla Tabulador por código
}
else //Para el resto de las teclas
{
e.Handled = true; // Interceptamos la pulsación para que no tenga lugar
data_grid.CurrentCell.ErrorText = "Solo se acepta formato de Hora.\n Ejemplo:\n 1:00 \n 2:00 a. m.\n 5:00 P. M.\n 15:00";
}
}
}
I created a KeyPress method to control the keys pressed by the user and only accept the ones that I defined in the method. Both columns in the Property: DefaultCellStyle - Format I have them with the format
hh:mm:ss tt
so that after the user finishes writing the time, I put it in that specified format.
Can I make this type of column without having to intercept each letter that is pressed by the user?
EDIT:
As in this example from @AsierVillanueva , creating a custom column which you can reuse as many times as you need it.
Note: I must NOT use a "DateTimePicker", the user must place it manually, because it will also load data from the database.