Monday 31 January 2011

Validar columnas de solo números o mayúsculas en DataGridView en C# y VB.NET

Es posible manejar la entrada de datos en cada columna del control DataGridView, usando el evento EditingControlShowing de dicho control, y es muy sencillo, así evitas por ejemplo en una columna que solo introduzcan letras mayúsculas que Copien&Peguen caracteres en minúsculas o que solo el campo sea numérico

En mi caso yo uso el tipo de columna, por ejemplo si la columna es numérica entonces asignarle el evento de solo números y si es alfa-numérico en mayúsculas le asignas la propiedad CharacterCasing a Upper ya que como sabras, las columnas de textos son simplementes TextBox

C#
/* * Creado por tttony 2010 * http://tttony.blogspot.com/ * * POR FAVOR NO BORRES ESTE COMENTARIO */

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{

if (e.Control is TextBox)
{
TextBox txt = e.Control as TextBox;

// Si la columna es numerica
if (object.ReferenceEquals(dataGridView1.CurrentCell.ValueType, typeof(System.Int32)))
{
// Asignar el evento de solo numeros a las columnas numericas
txt.KeyPress += OnlyNumbers_KeyPress;
}
else // o texto
{
/*
* Quitar el EventHandler del KeyPress para que permita escribir texto
*/
txt.KeyPress -= OnlyNumbers_KeyPress;
((TextBox)(e.Control)).CharacterCasing = CharacterCasing.Upper;
}
}
}

private void OnlyNumbers_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && e.KeyChar != 8) // Si no es numerico y si no es espacio
{
// Invalidar la accion
e.Handled = true;
// Enviar el sonido de beep de windows
System.Media.SystemSounds.Beep.Play();
}
}


VB.NET


Private Sub dataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs)

If TypeOf e.Control Is TextBox Then
Dim txt As TextBox = TryCast(e.Control, TextBox)

' Si la columna es numrica
If Object.ReferenceEquals(dataGridView1.CurrentCell.ValueType, GetType(System.Int32)) Then
' Asignar el evento de solo numeros a las columnas numericas
AddHandler txt.KeyPress, AddressOf OnlyNumbers_KeyPress
Else
' o texto
'
' * Quitar el EventHandler del KeyPress para que permita escribir texto
'

RemoveHandler txt.KeyPress, AddressOf OnlyNumbers_KeyPress
DirectCast(e.Control, TextBox).CharacterCasing = CharacterCasing.Upper
End If
End If
End Sub

Private Sub OnlyNumbers_KeyPress(sender As Object, e As KeyPressEventArgs)
If Not [Char].IsDigit(e.KeyChar) AndAlso e.KeyChar <> 8 Then
' Si no es numerico y si no es espacio
' Invalidar la accion
e.Handled = True
' Enviar el sonido de beep de windows
System.Media.SystemSounds.Beep.Play()
End If
End Sub


FUENTE

Publicado en tttony.blogspot.com

No comments:

Post a Comment