Primero, suponiendo que caja de texto es TextBox1, en KeyPress haz lo siguiente, para que sólo se pueda poner un punto como separador decimal. No se permite separador de miles. Independiente de la configuración regional de tu PC.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress
If e.KeyChar = Convert.ToChar(13) Then
Me.Button1.Focus()
ElseIf e.KeyChar = Convert.ToChar(8) Then ' se pulsó Retroceso
e.Handled = False
ElseIf (e.KeyChar = ","c) Then ' no permite la coma
e.Handled = True ' Handled = True, no permite; = False, si permite...
ElseIf (e.KeyChar = "."c) Then
Dim ctrl As TextBox = DirectCast(sender, TextBox)
If (ctrl.Text.IndexOf("."c) <> -1) Then ' sólo puede haber una coma
e.Handled = True
End If
ElseIf (e.KeyChar < "0"c Or e.KeyChar > "9"c) Then
' desechar los caracteres que no son dígitos
e.Handled = True
End If
End Sub
Luego, en el LostFocus haz lo siguiente: (Label1 es para expresar el resultado en el formulario)
Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles TextBox1.LostFocus
Me.Label1.Visible = False
Dim objTextBox As TextBox = CType(sender, TextBox)
If objTextBox.Text = "" Then
Exit Sub
Else
If IsNumeric(objTextBox.Text) Then
' Si es la "," s/Config.Reg. en decimales, constata que ya haya "." y que no
' haya aún "," para reemplazar el "." por la "," como separador decimal
If laComa = True Then
If objTextBox.Text.IndexOf("."c) <> -1 Then
If objTextBox.Text.IndexOf(","c) = -1 Then
' Reemplaza el "." por la "," para adaptar a la Conf.Reg. actual
Dim TestString As String = objTextBox.Text
objTextBox.Text = Replace(TestString, "."c, ","c)
End If
End If
End If
' Hago el formateo con puntos y comas, s/conf.regional actual
Dim a As Decimal = CDec(objTextBox.Text)
objTextBox.Text = a.ToString("N2")
Else
MessageBox.Show("No es una expresión numérica válida.", My.Application.Info.ProductName, _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
objTextBox.Text = "" : objTextBox.Focus()
End If
End If
End Sub
Espero te sea útil a tí u otros colegas que tengan igual dudas. Suerte. Bernardo.