Visual Basic.NET - TextBox para ingresar solo números y signo negativo

 
Vista:

TextBox para ingresar solo números y signo negativo

Publicado por Dario (1 intervención) el 28/05/2016 01:57:03
Hola, tengo el sig. codigo en un textbox para ingresar solo numeros

1
2
3
4
5
6
7
8
9
Private Sub txtcantidad_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtcantidad.KeyPress
	If Char.IsDigit(e.KeyChar) Then
		e.Handled = False
	ElseIf Char.IsControl(e.KeyChar) Then
		e.Handled = False
	Else
		e.Handled = True
	End If
End Sub

Lo que necesito es mejorar el codigo para que en el textbox ademas de solo numeros se pueda ingresar unicamente el signo - (negativo).

Muchas gracias
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
sin imagen de perfil
Val: 12
Ha disminuido su posición en 9 puestos en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

TextBox para ingresar solo números y signo negativo

Publicado por Alfredo (11 intervenciones) el 28/05/2016 02:05:52
Prueba con esto, este codigo te valida ademas otras cosas utiles, estan comentadas para mejor comprension:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
Private Sub cellTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cellTextBox.KeyPress
	' Referenciamos el control TextBox subyacente.
	'
	Dim tb As TextBox = TryCast(sender, TextBox)
	' Si la conversión ha fallado, abandonamos el procedimiento.
	'
	If (tb Is Nothing) Then
		e.Handled = True
		Return
	End If
 
	Dim isDecimal, isSign, isValidChar As Boolean
	Dim decimalSeparator As String = Nothing
	Select Case e.KeyChar
		Case "."c, ","c
			' Obtenemos el carácter separador decimal existente
			' actualmente en la configuración regional de Windows. 
			' 
		decimalSeparator = Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator
			' Hacemos que el carácter tecleado coincida con el
			' carácter separador existentente en la configuración
			' regional.
			'
			e.KeyChar = decimalSeparator.Chars(0)
			' Si el primer carácter que se teclea es el separador decimal,
			' o si bien, existe un signo en el primer carácter, envío la
			' combinación '0,'.
			'
			If (((tb.TextLength = 0) OrElse (tb.SelectionLength = tb.TextLength)) OrElse _
				((tb.TextLength = 1) AndAlso ((tb.Text.Contains("-")) OrElse (Text.Contains("+"))))) Then
				' NOTA: Envío la combinación "0," mediante el método Send,
				' para que en el código cliente se desencadenen los
				' eventos de teclado.
				'
				SendKeys.Send("{0}")
				SendKeys.Send("{" & decimalSeparator & "}")
				e.Handled = True
				Return
			End If
			' Es un carácter válido.
			'
			isDecimal = True
			isValidChar = True
		Case Else
			' Sólo se admitirán números y la tecla de retroceso.
			'
			Dim isDigit As Boolean = Char.IsDigit(e.KeyChar)
			Dim isControl As Boolean = Char.IsControl(e.KeyChar)
 
			If ((isDigit) OrElse (isControl)) Then
				isValidChar = True
			Else
				e.Handled = True
				Return
			End If
 
	End Select
	' Si es un carácter válido, y el texto del control
	' se encuentra totalmente seleccionado, elimino
	' el valor actual del control.
	'
	If ((isValidChar) And (tb.SelectionLength = tb.TextLength)) Then
		tb.Text = String.Empty
	End If
 
	If (isSign) Then
		' Admitimos los caracteres positivo y negativo, siempre y cuando
		' sea el primer carácter del texto, y no exista ya ningún otro
		' signo escrito en el control.
		'
		If ((tb.SelectionStart <> 0) OrElse _
			(tb.Text.IndexOf("-") >= 0) OrElse _
			(tb.Text.IndexOf("+") >= 0)) Then
			e.Handled = True
			Return
		End If
	End If
 
	If (isDecimal) Then
		' Si en el control hay ya escrito un separador decimal, 
		' deshechamos insertar otro separador más. 
		' 
		If (tb.Text.IndexOf(decimalSeparator) >= 0) Then
			e.Handled = True
			Return
		End If
	End If
 
End Sub
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