Visual Basic.NET - Mascara Numérica Textbox (colaboración)

 
Vista:

Mascara Numérica Textbox (colaboración)

Publicado por Haf (178 intervenciones) el 03/04/2008 11:19:16
Ayer en la mañana me dediqué a escribir este código el, cual permite ir dando formato de tipo numerico e inclusive colocar el signo negativo.
Tiene una falla que se puede mejorar y es que al inicio si se pulsa directamente un punto decimal (como para colocar 0.45) se queda en la parte decimal, Ya hoy no tengo más tiempo de terminarlo, también se podría cambiar la cantidad de decimales que se desean manejar. Si alguien lo termina o lo mejora, por favor me lo envía a mi correo [email protected]

Saludos

Public Class Form1
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = solonumeros(System.Convert.ToInt16(Asc(e.KeyChar)))
End Sub
Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
Me.TextBox1.Text = Mascara(TextBox1, e.KeyValue)
End Sub
Public Shared Function Mascara(ByVal txt As TextBox, ByVal tecla As Integer, Optional ByVal decimales As Integer = 2) As String
Dim SeparadorDecimal As String = My.Application.Culture.NumberFormat.NumberDecimalSeparator
Dim SeparadorMillar As String = My.Application.Culture.NumberFormat.NumberGroupSeparator
Dim ASCII As String = ""
txt.TextAlign = HorizontalAlignment.Right
If tecla >= 48 And tecla <= 57 Then
ASCII = CStr(tecla - 48)
End If
Dim Posicion_Cursor As Integer = txt.SelectionStart
If Trim(txt.Text.Length) <= 0 Then
Return Nothing
End If
If txt.Text.Length >= 3 Then
If Mid(txt.Text, Len(txt.Text) - 1) <> "00" Then
If tecla >= 48 And tecla <= 57 Then
If ASCII.Length > 1 Then
ASCII = Mid(ASCII, 2, 1)
End If
txt.Text = Mid(txt.Text, 1, Len(txt.Text) - 1) + ASCII
End If
End If
End If
If tecla = 109 Then 'signo menos
If txt.Text.Length >= 3 Then
If Mid(txt.Text, 1, 1) <> "-" Then
txt.Text = "-" + txt.Text
Else
txt.Text = txt.Text.Replace("-", "")
End If
SendKeys.Send("{END}")
End If
End If
If tecla = 190 Or tecla = 188 Then 'punto decimal (punto - coma)
If txt.Text.Length = 1 Then
txt.Text = "0" + SeparadorDecimal + "00"
txt.SelectionStart = InStr(txt.Text, SeparadorDecimal) '",")
Else
If SeparadorDecimal = "," Then
txt.Text = txt.Text.Replace(".,", SeparadorDecimal)
Else
txt.Text = txt.Text.Replace("..", SeparadorDecimal)
End If
txt.SelectionStart = InStr(txt.Text, SeparadorDecimal) ' ",")
End If
Else
If tecla <> 39 And tecla <> 37 And tecla <> 46 Then 'der,izq,del
txt.Text = FormatNumber(txt.Text, 2)
txt.SelectionStart = InStr(txt.Text, SeparadorDecimal) - 1
End If
If tecla = 46 Then 'delete
If Posicion_Cursor = Trim(txt.Text).Length - 2 Then 'borra el caracter de la coma decimal
txt.Text = Mid(txt.Text, 1, Posicion_Cursor) + SeparadorDecimal + Mid(txt.Text, Posicion_Cursor + 1, 2)
End If
If Mid(txt.Text, 1, 1) = SeparadorMillar Then 'borra el punto de unidades de mil
txt.Text = Mid(txt.Text, 2, Len(txt.Text))
End If
SendKeys.Send("{DOWN}")
End If
End If
Return txt.Text
End Function
Public Shared Function solonumeros(ByVal Kcode As Int16) As Boolean
If (Kcode >= 48 And Kcode <= 57) Or Kcode = 8 Or Kcode = 46 Or Kcode = 13 Or Kcode = 39 Or Kcode = 37 Or Kcode = 190 Or Kcode = 109 Then
Return False
Else
Return True
End If
End Function
End Class
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Modificación

Publicado por haf (178 intervenciones) el 03/04/2008 14:23:18
En la primera linea se debe agregar :

txt.Text = txt.Text.Replace(" ", "")
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Modificación

Publicado por haf (178 intervenciones) el 07/04/2008 17:18:24
Hice esta nueva rutina que está mejor :

Public Class Form1
Public Shared Function solonumeros(ByVal Kcode As Int16) As Boolean
If (Kcode >= 48 And Kcode <= 57) Or Kcode = 8 Or Kcode = 46 Or Kcode = 13 Or Kcode = 37 Or Kcode = 190 Then
Return False
Else
Return True
End If
End Function
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = solonumeros(System.Convert.ToInt16(Asc(e.KeyChar)))
End Sub
Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
Mascara(sender, e.KeyCode, 2)
End Sub
Private Sub Mascara(ByVal Txt As TextBox, ByVal valor As Integer, Optional ByVal decimales As Integer = 2)
Txt.TextAlign = HorizontalAlignment.Right
Dim Formato As String = "#,##0." & StrDup(decimales, "0")
Dim Negativo As Boolean = False
If Mid(Txt.Text, 1, 1) = "-" Then
Negativo = True
End If
Txt.Text = Txt.Text.Replace(" ", "")
If valor = 46 Then 'delete()
If Txt.Text.Length = 0 Then ' se ha borrado todo
Txt.Text = "0," & StrDup(decimales, "0") 'Replicate
Txt.Tag = ""
Else
If InStr(Txt.Text, ",") = 0 Then 'SE HA BORRADO EN LA POSCION DEL PUNTO DECIMAL
Txt.Text = Txt.Text.Replace(",", "")
Txt.Text = Txt.Text.Replace(".", "")
Try
Txt.Text = Mid(Txt.Text, 1, Len(Txt.Text) - decimales) + "," + Mid(Txt.Text, Len(Txt.Text) - (decimales - 1))
Catch ex As Exception
If Txt.Text.Length = 1 Then
Txt.Text = Txt.Text + "," + StrDup(decimales, "0")
End If
End Try
Try
Txt.Text = Format(CDbl(Txt.Text), Formato)
Catch ex As Exception ' solo en el caso que sea negativo
Txt.Text = Txt.Text.Replace(" ", "")
Txt.Text = Txt.Text.Replace(".", "")
Txt.Text = Txt.Text.Replace(",", "")
Txt.Text = Txt.Text.Replace("-", "")
Txt.Text = Txt.Text + "," + StrDup(decimales, "0")
If Negativo Then
Txt.Text = "-" + Txt.Text
End If
End Try
Txt.SelectionStart = Len(Txt.Text) - (decimales + 1)
Exit Sub
End If
Try
Txt.Text = Format(CDbl(Txt.Text), Formato)
Catch ex As Exception
Txt.Text = Txt.Text.Replace(".", "")
End Try
Txt.SelectionStart = Len(Txt.Text) - (decimales + 1)
End If
End If
If Trim(Txt.Text.Length) = 0 Or Mid(Txt.Text, 1, 1) = "." Then
Txt.Text = "0," & StrDup(decimales, "0") 'Replicate
Txt.Tag = ""
End If
Try
If (Mid(Txt.Tag, 1, 5) = "PUNTO") Then
If InStr(Txt.Tag, ",") > 0 Then ' HA LLEGADO A LA ÚLTIMA POSICION DECIMAL
If CInt(Mid(Txt.Tag, 7, 1)) >= decimales Then
Txt.Text = Mid(Txt.Text, 1, Len(Txt.Text) - 1)
End If
End If
End If
Txt.Text = Format(CDbl(Txt.Text), Formato)
Catch ex As Exception
Txt.Text = Txt.Text.Replace(" ", "")
Txt.Text = Txt.Text.Replace(",", "")
Txt.Text = Txt.Text.Replace(".", "")
Txt.Text = Mid(Txt.Text, 1, Len(Txt.Text) - decimales) + "," + Mid(Txt.Text, Len(Txt.Text) - decimales + 1)
Txt.Text = Format(CDbl(Txt.Text), Formato)
End Try
If valor <> 37 And valor <> 39 Then 'left rigth
Txt.SelectionStart = Len(Txt.Text) - (decimales + 1)
End If
Dim Posiciones(decimales) As String
If Mid(Txt.Tag, 1, 5) = "PUNTO" Then 'SE HA PULSADO EL PUNTO DECIMAL
Posiciones = Split(Txt.Tag, ",")
If Posiciones.Length = 1 Then
Else
Posiciones = Split(Txt.Tag, ",")
If CInt(Posiciones(1)) + 1 <= decimales Then
Txt.Tag = "PUNTO," + CStr(CInt(Posiciones(1)) + 1)
Txt.SelectionStart = Len(Txt.Text) - decimales + CInt(Posiciones(1))
Else
Txt.Tag = ""
End If
End If
End If
If valor = 190 Then 'punto decimal
Txt.SelectionStart = Len(Txt.Text) - decimales '2
Txt.Tag = "PUNTO,1"
End If
If valor = 109 Then 'menos -
If Txt.Text <> "0," & StrDup(decimales, "0") Then
If Mid(Txt.Text, 1, 1) = "-" Then
Txt.Text = Txt.Text.Replace("-", "")
Else
Txt.Text = "-" & Txt.Text
End If
Txt.SelectionStart = Len(Txt.Text) - (decimales + 1)
End If
End If
End Sub
Public Shared Function SinMascara(ByVal valor As String, Optional ByVal decimales As Integer = 2) As String
' hecho para sumar los campos el cual quita el formato y lo entrega en formato para suma
If valor.Length <= 0 Then
Return Nothing
End If
valor = valor.Replace(" ", "")
valor = valor.Replace(",", "")
valor = valor.Replace(".", "")
valor = Mid(valor, 1, Len(valor) - decimales) + "." + Mid(valor, Len(valor) - decimales + 1)
Return valor
End Function
End Class
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar