Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: luis456 en 11 Marzo 2016, 14:10 pm



Título: Condicionar Textbox a un rango determinado ??
Publicado por: luis456 en 11 Marzo 2016, 14:10 pm
Hola jejej a todos vuelvo con una chorrada

tengo varios TextBox y quiero que a partir del sexto no  me acepte números mayores a 45 y que cuando el usuario ponga un numero mayor a 45 no deje continuar el programa hasta poner un numero menor a 45 estoy con este codigo simplón pero deja que siga el programa auqnue le avise al usuario

Código
  1. Private Sub TextBox6_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox6.Validating
  2.        If (Int(TextBox6.Text) < 0 Or Int(TextBox6.Text) > 45) Then
  3.  
  4.            MsgBox("Numero mayor que 45 en casilla 6 introduzca numero correcto")
  5.  
  6.        End If
  7.  
  8.    End Sub  


saludos
Luis




Título: Re: Condicionar Textbox a un rango determinado ??
Publicado por: Eleкtro en 11 Marzo 2016, 14:48 pm
Hacer eso es reinventar la rueda, te sugiero usar un NumericUpDown, le pones valor máximo:45 valor mínimo:0 y ya lo tienes todo hecho.

De todas formas si sigues prefiriendo usar un TextBox dímelo y te explico como (con un ErrorProvider sería lo ideal).

Saludos!


Título: Re: Condicionar Textbox a un rango determinado ??
Publicado por: luis456 en 11 Marzo 2016, 15:34 pm
Hacer eso es reinventar la rueda, te sugiero usar un NumericUpDown, le pones valor máximo:45 valor mínimo:0 y ya lo tienes todo hecho.

De todas formas si sigues prefiriendo usar un TextBox dímelo y te explico como (con un ErrorProvider sería lo ideal).

Saludos!

Hola elektro bueno cambiar por  numeric me supondria hacer un monton de cambios en el codigo yo pensaba en algo mas facil , ya te aviso que hare, voy a mirar primero lo del error ese que pusiste

gracias

Luis


Título: Re: Condicionar Textbox a un rango determinado ??
Publicado por: Eleкtro en 11 Marzo 2016, 17:31 pm
yo pensaba en algo mas facil

Estoy casi seguro que la pregunta que has formulado ya la resolviste hace tiempo...
http://foro.elhacker.net/net/ayuda_como_hacer_para_validar_una_text_box_para_q_admita_solo_numeros-t429160.0.html;msg1994277#msg1994277
...no exactamente en ese post, pero no encuentro donde te mostré un ejemplo.

En fin, lo más sencillo es que uses un NumericUpDown, o heredar la Class de ese control para hacerlo más similar a un TextBox:

Código
  1. Public Class NumericTextBox : Inherits NumericUpDown
  2.  
  3.    Public Sub New()
  4.        MyBase.New()
  5.        MyBase.Controls(0).Visible = False
  6.    End Sub
  7.  
  8.    Protected Overrides Sub OnTextBoxResize(ByVal source As Object, ByVal e As EventArgs)
  9.        MyBase.Controls(0).Size = New Size(0, MyBase.ClientSize.Height)
  10.        MyBase.Controls(1).Size = New Size(MyBase.ClientSize.Width, MyBase.ClientSize.Height)
  11.    End Sub
  12.  
  13. End Class
(no está pulido, es un ejemplo breve)



Con un TextBox corriente puedes hacerlo de la siguiente manera:
Código
  1.    Private Sub TextBox1_Keypress(ByVal sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
  2.  
  3.        e.Handled = Not Char.IsNumber(e.KeyChar)
  4.  
  5.    End Sub
  6.  
  7.    Private Sub TextBox1_TextChanged(ByVal sender As Object, e As EventArgs) Handles TextBox1.TextChanged
  8.  
  9.        Dim ctrl As TextBox = DirectCast(sender, TextBox)
  10.  
  11.        If CInt(ctrl.Text) > 45 Then
  12.            ctrl.Text = "45"
  13.        End If
  14.  
  15.    End Sub





Título: Re: Condicionar Textbox a un rango determinado ??
Publicado por: luis456 en 11 Marzo 2016, 20:14 pm
Hola Elektro

Me decante por la segunda propuesta

Con un TextBox corriente puedes hacerlo de la siguiente manera:
Código
  1.    Private Sub TextBox1_Keypress(ByVal sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
  2.  
  3.        e.Handled = Not Char.IsNumber(e.KeyChar)
  4.  
  5.    End Sub
  6.  
  7.    Private Sub TextBox1_TextChanged(ByVal sender As Object, e As EventArgs) Handles TextBox1.TextChanged
  8.  
  9.        Dim ctrl As TextBox = DirectCast(sender, TextBox)
  10.  
  11.        If CInt(ctrl.Text) > 45 Then
  12.            ctrl.Text = "45"
  13.        End If
  14.  
  15.    End Sub

[/quote]


Pero claro siempre hay un pero jejje

error
La conversión de la cadena "" en el tipo 'Integer' no es válida.

Bien te enseño como tengo esto montado


Código
  1. Private Sub TextBox6_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox6.KeyPress, TextBox5.KeyPress, TextBox4.KeyPress, TextBox3.KeyPress, TextBox2.KeyPress, TextBox1.KeyPress
  2.        Button1.Enabled = ((TextBox1.TextLength > 0) And (TextBox2.TextLength > 0) And (TextBox3.TextLength > 0) And (TextBox4.TextLength > 0) And (TextBox5.TextLength > 0) And (TextBox6.TextLength > 0))
  3.        'And (TextBox7.TextLength > 0))
  4.  
  5.  
  6.        solonumeros(e)
  7.        If e.KeyChar = ChrW(Keys.Enter) Then
  8.            e.Handled = True
  9.            SendKeys.Send("{TAB}")
  10.  
  11.        End If
  12.  
  13.  
  14.    End Sub


puse tu código

de esta forma y si retrocede a 45 si pongo un numero mayor pero me salta el error


Código
  1.  Private Sub TextBox6_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox6.KeyPress, TextBox5.KeyPress, TextBox4.KeyPress, TextBox3.KeyPress, TextBox2.KeyPress, TextBox1.KeyPress
  2.        Button1.Enabled = ((TextBox1.TextLength > 0) And (TextBox2.TextLength > 0) And (TextBox3.TextLength > 0) And (TextBox4.TextLength > 0) And (TextBox5.TextLength > 0) And (TextBox6.TextLength > 0))
  3.        'And (TextBox7.TextLength > 0))
  4.        e.Handled = Not Char.IsNumber(e.KeyChar)
  5.  
  6.        solonumeros(e)
  7.        If e.KeyChar = ChrW(Keys.Enter) Then
  8.            e.Handled = True
  9.            SendKeys.Send("{TAB}")
  10.  
  11.        End If
  12.  
  13.    End Sub
  14.  
  15.    Private Sub TextBox6_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TextBox6.TextChanged
  16.  
  17.        Dim ctrl As TextBox = DirectCast(sender, TextBox)
  18.  
  19.        If CInt(ctrl.Text) > 45 Then
  20.            ctrl.Text = "45"
  21.        End If
  22.  
  23.    End Sub


Luis






Título: Re: Condicionar Textbox a un rango determinado ??
Publicado por: Eleкtro en 12 Marzo 2016, 05:31 am
error
La conversión de la cadena "" en el tipo 'Integer' no es válida.

Lo puedes solucionar evaluando si el string está vacío antes de usar la función CInt().

Código
  1. If String.IsNullOrEmpty(texto) then...
  2.  
  3.   If (CInt(texto) > 45) then...

O también puedes resolverlo utilizando la función Integer.TryParse() en lugar de CInt().

Saludos


Título: TEXTBOX
Publicado por: Filetito en 9 Noviembre 2021, 01:57 am
Hola como puedo hace para que un textBox me no me acepte numeros menores a 2020

tengo este pero este solo me funciona cuando es mayor a 2020 y necesito todo lo conttario

Private Sub txtnumero_TextChanged(sender As Object, e As EventArgs) Handles txtnumero.TextChanged
        If Val(txtnumero.Text) > 2020 Then
            MsgBox("Valor inválido", MsgBoxStyle.Information, "Información")
            txtnumero.Focus()
        End If
    End Sub
si me podrian ayudar porfavor :(


Título: Re: Condicionar Textbox a un rango determinado ??
Publicado por: Serapis en 9 Noviembre 2021, 22:11 pm
Tu pregunta es demasiado elemental (y la redacción contradictoria).
Simplemente cambia el operador de comparación de un 'mayor que' a un 'menor que' o quizás a un 'menor o igual que' (según sea el caso práctico).

Es tan elemental, que no queda más remedio que derivarte a la lectura. Cabe preguntarse si entiendes el código que has puesto...