elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [Ayuda] Como hacer para validar una text box para q admita solo numeros
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Ayuda] Como hacer para validar una text box para q admita solo numeros  (Leído 5,653 veces)
estebankpo15

Desconectado Desconectado

Mensajes: 25


Ver Perfil
[Ayuda] Como hacer para validar una text box para q admita solo numeros
« en: 1 Febrero 2015, 21:57 pm »

Hola estoy haciendo un sistema de validaciones para un final de la facultad, la cosa es q tengo una txtbox donde solo se deben ingresar numeros y al precionar guardar tendria que validad que lo q ingrese sea un numero.
Tambien habia pensado en que la textbox solo se puedan escribir numeros.
Alguien sabe alguna manera de solucionar esto?


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.817



Ver Perfil
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #1 en: 2 Febrero 2015, 08:21 am »

Alguien sabe alguna manera de solucionar esto?

Hay varías maneras.

La primera manera, y también las más eficiente, sería reemplazar el uso de un TextBox para utilizar el control más adecuado a tu situación actual y así seguir buenas prácticas de programación, tienes 2 posibilidades y ambas sin mayores complicaciones:
1) Un control de tipo NumericUpDown para rangos numéricos (ej: 0 - 100).
2) Un control de tipo MaskedTextbox para máscaras numéricas (ej: nnn.nnn.nnn.nnn).

Ahora bien, supongamos que por el motivo que sea prefieres omitir el consejo de arriba y seguir utilizando un TextBox, pues bien, soluciones:

1) Utilizar una expresión regular ("^\d+$") y evaluarla o utilizar los métodos de validación del Type Char, suscribiéndote al evento KeyPress para comprobar si el caracter es un número, pero esto sería una solución horrible ya que estariamos descuidando otros factores a tener en cuenta, de todas formas mostraré un ejemplo breve por si quieres ir a lo sencillo:
Código
  1.    ''' <summary>
  2.    ''' Handles the KeyPress event of the TextBox1 control.
  3.    ''' </summary>
  4.    ''' <param name="sender">The source of the event.</param>
  5.    ''' <param name="e">The <see cref="KeyPressEventArgs"/> instance containing the event data.</param>
  6.    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) _
  7.    Handles TextBox1.KeyPress
  8.  
  9.        e.Handled = Not Char.IsNumber(e.KeyChar)
  10.  
  11.    End Sub

2) Cómo he dicho la solución anterior es horrible, ¿por qué?, por que para evitar completamente que se puede añadir "X" caracter en un TextBox corriente, debes tener varias cosas más en cuenta, como el menú contextual (Edit menu), los atajos de teclado Windows (System-wide Hotkeys), y la característica de soltar y arrastrar (Drag&Drop) en caso de que desees añadirle dicha funcionalidad.

Así pues, otra manera que aportaría mayor eficiencia, libertad, y personalización, sería definir un set de caracteres permitidos, y cancelar la escritura del caracter en el evento KeyPress cuando dicho caracter no se encuentre dentro de los caracteres permitidos:

Para ello he implementado el uso de dicha técnica desarrollando un user-control (el cual se puede mejorar en muchos sentidos, ya que no le puse demasiado empeño en la elaboración del código).

Modo de empleo:
Código
  1. Imports WindowsApplication1.ElektroTextBox
  2.  
  3. Public Class TestForm
  4.  
  5.    Private WithEvents etb As New ElektroTextBox
  6.  
  7.    Private Sub TestForm_Load() Handles MyBase.Load
  8.  
  9.        With Me.etb
  10.            .AllowDrop = True
  11.            .DisableEditMenu = True
  12.            .CurrentCharSet = CharSet.StandardAlphabetic Or
  13.                              CharSet.StandardSymbols Or
  14.                              CharSet.Numeric
  15.  
  16.        End With
  17.  
  18. #If DEBUG Then
  19.        Debug.WriteLine("ElektroTextBox has been initialized...")
  20.        Debug.WriteLine(String.Format("Current CharSet Int: {0}", CStr(etb.CurrentCharSet)))
  21.        Debug.WriteLine(String.Format("Current CharSet Str: {0}", etb.CurrentCharSet))
  22.        Debug.WriteLine(String.Format("CharSet Characters : {0}", String.Join(String.Empty, etb.CurrentCharSetChars)))
  23. #End If
  24.  
  25.        MyBase.Controls.Add(Me.etb)
  26.  
  27.    End Sub
  28.  
  29. End Class

Source:
Nota: Las características del menú contextual se pueden manejar también con los mensajes de Windows que procesa la ventana, WM_COPY, WM_CUT, y WM_PASTE, pero he preferido omitir la intercepción y el procesamiento de mensajes de Windows para no cargar más de la cuenta el user-control con operaciones innecesarias (y tambien porque como ya dije no le he puesto tanto empeño para su elaboración).

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-February-2015
  4. ' ***********************************************************************
  5. ' <copyright file="ElektroTextBox.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.ComponentModel
  13.  
  14. #End Region
  15.  
  16. ''' <summary>
  17. ''' An extended TextBox with character validation capabilities.
  18. ''' </summary>
  19. Public NotInheritable Class ElektroTextBox : Inherits TextBox
  20.  
  21. #Region " Properties "
  22.  
  23.    ''' <summary>
  24.    ''' Gets or sets a value indicating whether
  25.    ''' the default <see cref="ContextMenuStrip"/> for this <see cref="ElektroTextBox"/> instance is disabled.
  26.    ''' </summary>
  27.    ''' <value>
  28.    ''' <c>true</c> if <see cref="ContextMenuStrip"/> is disabled for this <see cref="ElektroTextBox"/> instance;
  29.    ''' <c>false</c> otherwise.</value>
  30.    Public Property DisableEditMenu As Boolean = False
  31.  
  32.    ''' <summary>
  33.    ''' An empty <see cref="ContextMenuStrip"/> that replaces the default <see cref="ContextMenuStrip"/>
  34.    ''' when <see cref="DisableEditMenu"/> property is set to <c>true</c>.
  35.    ''' of this <see cref="ElektroTextBox"/> instance.
  36.    ''' </summary>
  37.    Private ReadOnly emptynessContextMenuStrip As ContextMenuStrip
  38.  
  39.    ''' <summary>
  40.    ''' Gets or sets the character-set that contains the allowed characters to fill this <see cref="ElektroTextBox"/> instance.
  41.    ''' </summary>
  42.    ''' <value>The character-set that contains the allowed characters to fill this <see cref="ElektroTextBox"/> instance.</value>
  43.    <Description("The characters that are allowed to fill this ElektroTextBox")>
  44.    Public Property CurrentCharSet As CharSet
  45.        Get
  46.            Return Me.currentCharSet1
  47.        End Get
  48.        Set(ByVal value As CharSet)
  49.            Me.currentCharSet1 = value
  50.            Me.currentCharSetChars1 = Me.GetCharSetChars(value)
  51.        End Set
  52.    End Property
  53.    ''' <summary>
  54.    ''' The character-set that contains the allowed characters to fill this <see cref="ElektroTextBox"/> instance.
  55.    ''' </summary>
  56.    Private currentCharSet1 As CharSet = CharSet.StandardAlphabetic Or CharSet.StandardSymbols Or CharSet.Numeric
  57.  
  58.    ''' <summary>
  59.    ''' Gets the characters of the current character-set.
  60.    ''' </summary>
  61.    ''' <value>The characters of the current character-set.</value>
  62.    Public ReadOnly Property CurrentCharSetChars As IEnumerable(Of Char)
  63.        Get
  64.            Return Me.currentCharSetChars1
  65.        End Get
  66.    End Property
  67.    ''' <summary>
  68.    ''' The characters of the current character-set.
  69.    ''' </summary>
  70.    Private currentCharSetChars1 As IEnumerable(Of Char) = Me.GetCharSetChars(Me.currentCharSet1)
  71.  
  72.    ''' <summary>
  73.    ''' Determines whether a pasting operation is requested.
  74.    ''' </summary>
  75.    Private isPasteRequested As Boolean = False
  76.  
  77.    ''' <summary>
  78.    ''' Determines whether the 'Enter' key is requested.
  79.    ''' </summary>
  80.    Private isEnterKeyRequested As Boolean = False
  81.  
  82.    ''' <summary>
  83.    ''' Determines whether the 'Backspace' key is requested.
  84.    ''' </summary>
  85.    Private isBackspacekeyRequested As Boolean = False
  86.  
  87.    ''' <summary>
  88.    ''' Determines whether an unknown key is requested.
  89.    ''' </summary>
  90.    Private isUnknownKeyRequested As Boolean = False
  91.  
  92.    ''' <summary>
  93.    ''' Contains pre-defined <see cref="ElektroTextBox"/> character sets.
  94.    ''' </summary>
  95.    Public NotInheritable Class CharSets
  96.  
  97.        ''' <summary>
  98.        ''' Gets the standard alphabetic character set.
  99.        ''' </summary>
  100.        ''' <value>The standard alphabetic character set.</value>
  101.        Public Shared ReadOnly Property CharSetStandardAlpha As IEnumerable(Of Char)
  102.            Get
  103.                Return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  104.            End Get
  105.        End Property
  106.  
  107.        ''' <summary>
  108.        ''' Gets the standard symbols character set.
  109.        ''' </summary>
  110.        ''' <value>The standard symbols character set.</value>
  111.        Public Shared ReadOnly Property CharSetStandardSymbols As IEnumerable(Of Char)
  112.            Get
  113.                Return """|@·#$~%&¬/\()[]{}<>?!,;.:'¨^-_+=*"
  114.            End Get
  115.        End Property
  116.  
  117.        ''' <summary>
  118.        ''' Gets the numerical character set.
  119.        ''' </summary>
  120.        ''' <value>The numerical character set.</value>
  121.        Public Shared ReadOnly Property CharSetNumeric As IEnumerable(Of Char)
  122.            Get
  123.                Return "1234567890"
  124.            End Get
  125.        End Property
  126.  
  127.        ''' <summary>
  128.        ''' Gets the Spanish alphabetic character set.
  129.        ''' </summary>
  130.        ''' <value>The Spanish alphabetic character set.</value>
  131.        Public Shared ReadOnly Property CharSetSpanishAlpha As IEnumerable(Of Char)
  132.            Get
  133.                Return CharSetStandardAlpha.Concat("ñáéíóúàèìòùäëïöüÑÁÉÍÓÚÀÈÌÒÙÄËÏÖÜ")
  134.            End Get
  135.        End Property
  136.  
  137.        ''' <summary>
  138.        ''' Gets the Spanish symbols character set.
  139.        ''' </summary>
  140.        ''' <value>The Spanish symbols character set.</value>
  141.        Public Shared ReadOnly Property CharSetSpanishSymbols As IEnumerable(Of Char)
  142.            Get
  143.                Return CharSetStandardSymbols.Concat("ºª¿¡`´€")
  144.            End Get
  145.        End Property
  146.  
  147.        ''' <summary>
  148.        ''' Gets the Catalonian alphabetic character set.
  149.        ''' </summary>
  150.        ''' <value>The Catalonian alphabetic character set.</value>
  151.        Public Shared ReadOnly Property CharSetCatalonianAlpha As IEnumerable(Of Char)
  152.            Get
  153.                Return CharSetStandardAlpha.Concat("çáéíóúàèìòùäëïöüÇÁÉÍÓÚÀÈÌÒÙÄËÏÖÜ")
  154.            End Get
  155.        End Property
  156.  
  157.        ''' <summary>
  158.        ''' Gets the Catalonian symbols character set.
  159.        ''' </summary>
  160.        ''' <value>The Catalonian symbols character set.</value>
  161.        Public Shared ReadOnly Property CharSetCatalonianSymbols As IEnumerable(Of Char)
  162.            Get
  163.                Return CharSetSpanishSymbols
  164.            End Get
  165.        End Property
  166.  
  167.        ''' <summary>
  168.        ''' Gets the roman numerals characters set.
  169.        ''' </summary>
  170.        ''' <value>The roman numerals characters set.</value>
  171.        Public Shared ReadOnly Property CharSetRomanNumerals As IEnumerable(Of Char)
  172.            Get
  173.                Return "IVXLCDM"
  174.            End Get
  175.        End Property
  176.  
  177.    End Class
  178.  
  179. #End Region
  180.  
  181. #Region " Enumerations "
  182.  
  183.    ''' <summary>
  184.    ''' Specifies a <see cref="ElektroTextBox"/> character set.
  185.    ''' These values can be combined.
  186.    ''' </summary>
  187.    <FlagsAttribute>
  188.    Public Enum CharSet As Integer
  189.  
  190.        ''' <summary>
  191.        ''' Any character set.
  192.        ''' This will disable any character typing on the <see cref="ElektroTextBox"/> instance.
  193.        ''' </summary>
  194.        None = 0
  195.  
  196.        ''' <summary>
  197.        ''' Standard alphabetic characters.
  198.        ''' </summary>
  199.        StandardAlphabetic = 1
  200.  
  201.        ''' <summary>
  202.        ''' Standard symbol characters.
  203.        ''' </summary>
  204.        StandardSymbols = 2
  205.  
  206.        ''' <summary>
  207.        ''' Numeric characters.
  208.        ''' </summary>
  209.        Numeric = 4
  210.  
  211.        ''' <summary>
  212.        ''' Spanish alphabetic characters.
  213.        ''' </summary>
  214.        SpanishAlphabetic = 8
  215.  
  216.        ''' <summary>
  217.        ''' Spanish symbol characters.
  218.        ''' </summary>
  219.        SpanishSymbols = 16
  220.  
  221.        ''' <summary>
  222.        ''' Catalonian alphabetic characters.
  223.        ''' </summary>
  224.        CatalonianAlphabetic = 32
  225.  
  226.        ''' <summary>
  227.        ''' Catalonian symbol characters.
  228.        ''' </summary>
  229.        CatalonianSymbols = 64
  230.  
  231.        ''' <summary>
  232.        ''' Roman numerals characters.
  233.        ''' </summary>
  234.        RomanNumerals = 128
  235.  
  236.    End Enum
  237.  
  238. #End Region
  239.  
  240. #Region " Constructors "
  241.  
  242.    ''' <summary>
  243.    ''' Initializes a new instance of the <see cref="ElektroTextBox"/> class.
  244.    ''' </summary>
  245.    Public Sub New()
  246.        Me.emptynessContextMenuStrip = New ContextMenuStrip
  247.    End Sub
  248.  
  249. #End Region
  250.  
  251. #Region " Overriden Events "
  252.  
  253.    ''' <summary>
  254.    ''' Raises the <see cref="E:Control.Enter"/> event.
  255.    ''' </summary>
  256.    ''' <param name="e">An <see cref="T:EventArgs"/> that contains the event data.</param>
  257.    Protected Overrides Sub OnEnter(ByVal e As EventArgs)
  258.  
  259.        Me.ToggleEditMenu(Me.DisableEditMenu)
  260.        MyBase.OnEnter(e)
  261.  
  262.    End Sub
  263.  
  264.    ''' <summary>
  265.    ''' Raises the <see cref="E:Control.MouseEnter"/> event.
  266.    ''' </summary>
  267.    ''' <param name="e">An <see cref="T:EventArgs" /> that contains the event data.</param>
  268.    Protected Overrides Sub OnMouseEnter(ByVal e As EventArgs)
  269.  
  270.        Me.ToggleEditMenu(Me.DisableEditMenu)
  271.        MyBase.OnMouseEnter(e)
  272.  
  273.    End Sub
  274.  
  275.    ''' <summary>
  276.    ''' Raises the <see cref="E:Control.KeyDown"/> event.
  277.    ''' </summary>
  278.    ''' <param name="e">A <see cref="T:KeyEventArgs"/> that contains the event data.</param>
  279.    Protected Overrides Sub OnKeyDown(ByVal e As KeyEventArgs)
  280.  
  281.        If (e.KeyCode = Keys.Enter) Then ' Enter key.
  282.            ' Let handle the 'Enter' key on 'KeyPress' event for proper evaluation.
  283.            Me.isEnterKeyRequested = True
  284.  
  285.        ElseIf (e.KeyCode = Keys.Back) Then ' Backspace key.
  286.            ' Let handle the 'Enter' key on 'KeyPress' event for proper evaluation..
  287.            Me.isBackspacekeyRequested = True
  288.  
  289.        ElseIf (e.KeyCode = Keys.C) AndAlso (e.Modifiers = Keys.Control) Then ' CTRL+C hotkey.
  290.            ' Allow to copy text.
  291.            e.Handled = False
  292.            e.SuppressKeyPress = True
  293.            MyBase.Copy()
  294.  
  295.        ElseIf (e.KeyCode = Keys.X) AndAlso (e.Modifiers = Keys.Control) Then ' CTRL+X hotkey.
  296.            ' Allow to cut text.
  297.            e.Handled = False
  298.            e.SuppressKeyPress = True
  299.            MyBase.Cut()
  300.  
  301.        ElseIf (e.KeyCode = Keys.V) AndAlso (e.Modifiers = Keys.Control) Then ' CTRL+V hotkey.
  302.            ' Let handle the text pasting on 'KeyPress' event for proper character(s) evaluation.
  303.            Me.isPasteRequested = True
  304.  
  305.        Else ' Unhandled character.
  306.            ' Let handle the unknown char on 'KeyPress' event for proper character evaluation.
  307.            Me.isUnknownKeyRequested = True
  308.  
  309.        End If
  310.  
  311. #If DEBUG Then ' Helper.
  312.        Debug.WriteLine(String.Format("Modifiers:{0} KeyCode:{1} KeyData:{2} KeyValue:{3} ",
  313.                                      e.Modifiers.ToString,
  314.                                      e.KeyCode.ToString,
  315.                                      e.KeyData.ToString,
  316.                                      e.KeyValue.ToString))
  317. #End If
  318.  
  319.        MyBase.OnKeyDown(e)
  320.  
  321.    End Sub
  322.  
  323.    ''' <summary>
  324.    ''' Raises the <see cref="E:Control.KeyPress"/> event.
  325.    ''' </summary>
  326.    ''' <param name="e">A <see cref="T:KeyPressEventArgs"/> that contains the event data.</param>
  327.    Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
  328.  
  329.        If isPasteRequested Then
  330.            ' Allow to paste text only if all characters are allowed characters.
  331.            e.Handled = Not Me.StringHasNonAllowedChars(Clipboard.GetText, Me.currentCharSetChars1)
  332.            Me.isPasteRequested = False
  333.  
  334.        ElseIf isBackspacekeyRequested Then
  335.            ' Allow character deletion.
  336.            e.Handled = False
  337.            Me.isBackspacekeyRequested = False
  338.  
  339.        ElseIf isEnterKeyRequested Then
  340.            ' Allow the effects of Enter key.
  341.            e.Handled = False
  342.            Me.isEnterKeyRequested = False
  343.  
  344.        ElseIf isUnknownKeyRequested Then
  345.            ' Allow unknown character only if it's an allowed character.
  346.            e.Handled = Not Me.StringHasNonAllowedChars({Convert.ToChar(e.KeyChar)}, Me.currentCharSetChars1)
  347.            Me.isUnknownKeyRequested = False
  348.  
  349.        End If
  350.  
  351.        MyBase.OnKeyPress(e)
  352.  
  353.    End Sub
  354.  
  355.    ''' <summary>
  356.    ''' Raises the <see cref="E:Control.DragEnter"/> event.
  357.    ''' </summary>
  358.    ''' <param name="drgevent">A <see cref="T:DragEventArgs"/> that contains the event data.</param>
  359.    Protected Overrides Sub OnDragEnter(ByVal drgevent As DragEventArgs)
  360.  
  361.        If MyBase.AllowDrop Then
  362.  
  363.            Select Case True
  364.  
  365.                Case drgevent.Data.GetDataPresent(DataFormats.Text) ' ANSI text.
  366.                    drgevent.Effect = DragDropEffects.Copy ' Drop text from dragged source.
  367.  
  368.                Case Else
  369.                    ' Do Nothing.
  370.  
  371.            End Select
  372.  
  373.        End If
  374.  
  375.        MyBase.OnDragEnter(drgevent)
  376.  
  377.    End Sub
  378.  
  379.    ''' <summary>
  380.    ''' Raises the <see cref="E:Control.DragDrop"/> event.
  381.    ''' </summary>
  382.    ''' <param name="drgevent">A <see cref="T:DragEventArgs"/> that contains the event data.</param>
  383.    Protected Overrides Sub OnDragDrop(ByVal drgevent As DragEventArgs)
  384.  
  385.        If MyBase.AllowDrop Then
  386.  
  387.            Select Case True
  388.  
  389.                Case drgevent.Data.GetDataPresent(DataFormats.Text) ' ANSI text.
  390.                    Dim dropString As String = DirectCast(drgevent.Data.GetData(DataFormats.Text), String)
  391.  
  392.                    ' Allow text drop only if all characters are numeric.
  393.                    If Me.StringHasNonAllowedChars(dropString, Me.currentCharSetChars1) Then
  394.                        MyBase.Text = dropString
  395.                    End If
  396.  
  397.                Case Else
  398.                    ' Do Nothing.
  399.  
  400.            End Select
  401.  
  402.        End If
  403.  
  404.        MyBase.OnDragDrop(drgevent)
  405.  
  406.    End Sub
  407.  
  408. #End Region
  409.  
  410. #Region " Private Methods "
  411.  
  412.    ''' <summary>
  413.    ''' Toggles the edit menu visibility.
  414.    ''' </summary>
  415.    ''' <param name="enable">
  416.    ''' If set to <c>true</c>, restores the default <see cref="ContextMenuStrip"/> for this <see cref="ElektroTextBox"/> instance.
  417.    ''' </param>
  418.    Private Sub ToggleEditMenu(ByVal enable As Boolean)
  419.  
  420.        If (enable) AndAlso (MyBase.ContextMenuStrip Is Nothing) Then
  421.            ' Disable default Copy/Cut/Paste contextmenu.
  422.            MyBase.ContextMenuStrip = Me.emptynessContextMenuStrip
  423.  
  424.        ElseIf Not (enable) AndAlso (MyBase.ContextMenuStrip IsNot Nothing) Then
  425.            ' Restore default edit contextmenu.
  426.            MyBase.ContextMenuStrip = Nothing
  427.  
  428.        Else
  429.            ' Do Nothing.
  430.  
  431.        End If
  432.  
  433.    End Sub
  434.  
  435.    ''' <summary>
  436.    ''' Gets the characters of a <see cref="CharSet"/>.
  437.    ''' </summary>
  438.    ''' <param name="charSet">The <see cref="CharSet"/>.</param>
  439.    ''' <returns>The characters of a <see cref="CharSet"/>.</returns>
  440.    Private Function GetCharSetChars(ByVal charSet As CharSet) As IEnumerable(Of Char)
  441.  
  442.        Dim chars As IEnumerable(Of Char) = String.Empty
  443.  
  444.        If charSet.HasFlag(charSet.None) Then
  445.            ' Do Nothing.
  446.        End If
  447.  
  448.        If charSet.HasFlag(charSet.StandardAlphabetic) Then
  449.            chars = chars.Concat(CharSets.CharSetStandardAlpha)
  450.        End If
  451.  
  452.        If charSet.HasFlag(charSet.StandardSymbols) Then
  453.            chars = chars.Concat(CharSets.CharSetStandardSymbols)
  454.        End If
  455.  
  456.        If charSet.HasFlag(charSet.Numeric) Then
  457.            chars = chars.Concat(CharSets.CharSetNumeric)
  458.        End If
  459.  
  460.        If charSet.HasFlag(charSet.SpanishAlphabetic) Then
  461.            chars = chars.Concat(CharSets.CharSetSpanishAlpha)
  462.        End If
  463.  
  464.        If charSet.HasFlag(charSet.SpanishSymbols) Then
  465.            chars = chars.Concat(CharSets.CharSetSpanishSymbols)
  466.        End If
  467.  
  468.        If charSet.HasFlag(charSet.CatalonianAlphabetic) Then
  469.            chars = chars.Concat(CharSets.CharSetCatalonianAlpha)
  470.        End If
  471.  
  472.        If charSet.HasFlag(charSet.CatalonianSymbols) Then
  473.            chars = chars.Concat(CharSets.CharSetCatalonianSymbols)
  474.        End If
  475.  
  476.        If charSet.HasFlag(charSet.RomanNumerals) Then
  477.            chars = chars.Concat(CharSets.CharSetRomanNumerals)
  478.        End If
  479.  
  480.        Return (From c As Char In chars Order By c.ToString Ascending Distinct)
  481.  
  482.    End Function
  483.  
  484.    ''' <summary>
  485.    ''' Determines whether the specified string has non allowed characters for this <see cref="ElektroTextBox"/> instance.
  486.    ''' </summary>
  487.    ''' <param name="characters">The characters that will be evaluated.</param>
  488.    ''' <param name="allowedChars">The allowed characters.</param>
  489.    ''' <returns><c>true</c> if all the characters of the specified string satisfy the condition;
  490.    ''' <c>false</c> otherwise.</returns>
  491.    Private Function StringHasNonAllowedChars(ByVal characters As IEnumerable(Of Char),
  492.                                              ByVal allowedChars As IEnumerable(Of Char)) As Boolean
  493.  
  494.        Return characters.All(Function(c As Char)
  495.                                  Return allowedChars.Contains(c, Nothing)
  496.                              End Function)
  497.  
  498.    End Function
  499.  
  500. #End Region
  501.  
  502. End Class

Saludos.


« Última modificación: 2 Febrero 2015, 10:18 am por Eleкtro » En línea

__Alvaro 2015__

Desconectado Desconectado

Mensajes: 164



Ver Perfil WWW
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #2 en: 6 Febrero 2015, 06:23 am »

Puedes utilizar la Función "IsNumeric", ejemplo:

Código
  1.  
  2. Dim cadena As String = ""
  3.  
  4. Console.WriteLine("Ingrese un numero:")
  5. cadena = Console.ReadLine()
  6.  
  7. If IsNumeric(cadena) Then
  8.    Console.WriteLine("Es numero")
  9. Else
  10.    Console.WriteLine("No es numero")
  11. End If
  12. Console.WriteLine("Presione enter para continuar..")
  13. Console.ReadLine()
  14.  
  15.  

Saludos  ::)
En línea

"Pasión por la programación"
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.817



Ver Perfil
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #3 en: 6 Febrero 2015, 07:04 am »

Puedes utilizar la Función "IsNumeric", ejemplo:

Lo que sugieres son malas prácticas de programación, al utilizar un wrapper de VB6.

¿Has leido mi post?, arriba puse un ejemplo sencillo de como usar su equivalente en .Net, utilizando el método Char.IsNumber()

Por otor lado, para comrprobar si un String es numérico, el equivalente de "IsNumeric" en .Net sería utilizar el método Parse/TryParse del Datatype específico, por ejemplo:

Código
  1. If Integer.TryParse("123", New Integer) Then
  2. ' Es un número.
  3. End If

...Pero eso es algo innecesario al igual que la función IsNumeric, ya que la pregunta no requiere comprobar un String, sino un único Char.

Este comentario es con la intención de orientar a aquellas personas que sugieren la utilización de la función IsNumeric, al igual que Left, Right, y todas esas cosas obsoletas, Porfavor, eviten su utilización.

Saludos!
« Última modificación: 6 Febrero 2015, 07:09 am por Eleкtro » En línea

__Alvaro 2015__

Desconectado Desconectado

Mensajes: 164



Ver Perfil WWW
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #4 en: 6 Febrero 2015, 08:12 am »

Citar
Lo que sugieres son malas prácticas de programación, al utilizar un wrapper de VB6.

Eso hoy en día es una leyenda, antes si era cierto, por que el CLR de VB6 ejecutaba mucho código basura, posteriormente se desarrollo (por así decirlo, .NET), y se determino, que un "wrapper" siendo un objeto a diferencia de un dato primitivo te brinda métodos que son de gran utilidad, para el manejo de primitivos.
Por esta razón, es que se utilizan esta y otras funciones en la gran mayoría de los lenguajes, sin considerarlos "deprecated".

Igual estoy a favor de que se brinden alternativas, y admiro tu esmerada respuesta Elektro.

Citar
...Pero eso es algo innecesario al igual que la función IsNumeric, ya que la pregunta no requiere comprobar un String, sino un único Char.

El evento de escucha "KeyPress" no siempre funciona bien.

Saludos.
En línea

"Pasión por la programación"
luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #5 en: 6 Febrero 2015, 08:26 am »

Yo lo solucione de esta manera espero te sirva


Código
  1.  Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
  2.        solonumeros(e)
  3.        If e.KeyChar = ChrW(Keys.Enter) Then
  4.            e.Handled = True
  5.            SendKeys.Send("{TAB}")
  6.        End If
  7.    End Sub


luis

En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.817



Ver Perfil
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #6 en: 6 Febrero 2015, 10:49 am »

Eso hoy en día es una leyenda, antes si era cierto, por que el CLR de VB6 ejecutaba mucho código basura, posteriormente se desarrollo (por así decirlo, .NET), y se determino, que un "wrapper" siendo un objeto a diferencia de un dato primitivo te brinda métodos que son de gran utilidad, para el manejo de primitivos.
Por esta razón, es que se utilizan esta y otras funciones en la gran mayoría de los lenguajes, sin considerarlos "deprecated".

No soy una persona de afirmar leyendas, ya que no es ninguna leyenda, es tal y como es;
la razón de que Microsoft decidiese desarrollar ese namespace fue con la finalidad de que a los desarrolladores del antiguo VB6 les fuera más comodo actualizarse a VB.Net, hallando así los mismos métodos que utilizaban en el antiguo VB6 al sentirse familiriazados con éstos, un motivo comprensible, pero eso no significa que lo correcto sea usarlos, ni que deban ser usados.

Obviamente al denominar como "obsoleto" los miembros de ese namespace no lo digo porque esté escrito en VB6, ya que es todo código .Net, y algunas de las llamadas de los métodos del namespace Microsoft.VisualBasic son simplemente wrappers de funcionalidades de otros métodos existentes de la librería de classes de .Net Framework, lo que podemos denominar "puro código .Net", pero otras muchas NO lo son, son "puro código basura".

Ya que para casi todos los métodos/funciones del namespace VisualBasic, existen versiones mucho más robustas en el resto de la librería de classes de .Net Framework.
Un ejemplo de esto sería la función "Val", comparándola con la función "TryParse" de un Datatype específico.

Los métodos/funciones del namespace VisualBasic usan técnicas consideradas deprecadas por el propio Microsoft (bueno, y por "la industria de la programación"), es decir, malas prácticas de programación , como por ejemplo el uso del GOTO y los Labels al proporcionar una estructura insegura al código,
para no dejarme nada en el tintero, esto es solo un ejemplo de dichas malas prácticas, y es algo que obviamente también se utiliza en el namespace System (lo nombro al ser el namespace que usaré para la siguiente comparación de abajo), pero con una menor frecuencia en al relación de veces usada * cantitad de miembros, siendo 155 veces en el namespace VisualBasic en 179 archivos desamblados, es decir, cerca del 87% de las classes utilizan esta mala práctica, y 915 veces en el namespace System en 1.681 archivos desamblados, alrededor de un 54% de las classes, pero vuelvo a recordar que solo era un ejemplo, no nos fijemos solo en este aspecto, ya que hay otras cosas del namespace VisualBasic que son "basura".

Y por esos motivos no es lo más conveniente usar esos wrappers.

Te mostraré algo, haciendo uso de la técnica Reflection, estas son las instrucciones de la función "Val" del namespace Microsoft.VisualBasic,

(omitiendo las instrucciones de varios métodos más como ChrW, etc, para no hacer más largo este post)

Código
  1. Public Shared Function Val(ByVal InputStr As String) As Double
  2.    Dim ch As Char
  3.    Dim num As Integer
  4.    Dim num2 As Integer
  5.    Dim num3 As Integer
  6.    Dim length As Integer
  7.    Dim num8 As Double
  8.    If (InputStr Is Nothing) Then
  9.        length = 0
  10.    Else
  11.        length = InputStr.Length
  12.    End If
  13.    Dim num4 As Integer = 0
  14.    Do While (num4 < length)
  15.        ch = InputStr.Chars(num4)
  16.        Select Case ch
  17.            Case ((ChrW(9) AndAlso ChrW(10)) AndAlso ((ChrW(13) AndAlso " "c) AndAlso ChrW(12288)))
  18.                Exit Select
  19.        End Select
  20.        num4 += 1
  21.    Loop
  22.    If (num4 >= length) Then
  23.        Return 0
  24.    End If
  25.    ch = InputStr.Chars(num4)
  26.    If (ch = "&"c) Then
  27.        Return Conversion.HexOrOctValue(InputStr, (num4 + 1))
  28.    End If
  29.    Dim flag As Boolean = False
  30.    Dim flag2 As Boolean = False
  31.    Dim flag3 As Boolean = False
  32.    Dim y As Double = 0
  33.    ch = InputStr.Chars(num4)
  34.    Select Case ch
  35.        Case "-"c
  36.            flag3 = True
  37.            num4 += 1
  38.            Exit Select
  39.        Case "+"c
  40.            num4 += 1
  41.            Exit Select
  42.    End Select
  43.    Do While (num4 < length)
  44.        ch = InputStr.Chars(num4)
  45.        Dim ch3 As Char = ch
  46.        If (((ch3 = ChrW(9)) OrElse (ch3 = ChrW(10))) OrElse (((ch3 = ChrW(13)) OrElse (ch3 = " "c)) OrElse (ch3 = ChrW(12288)))) Then
  47.            num4 += 1
  48.        Else
  49.            If (ch3 = "0"c) Then
  50.                If ((num <> 0) OrElse flag) Then
  51.                    num8 = (((num8 * 10) + CDbl(ch)) - 48)
  52.                    num4 += 1
  53.                    num += 1
  54.                Else
  55.                    num4 += 1
  56.                End If
  57.                Continue Do
  58.            End If
  59.            If ((ch3 >= "1"c) AndAlso (ch3 <= "9"c)) Then
  60.                num8 = (((num8 * 10) + CDbl(ch)) - 48)
  61.                num4 += 1
  62.                num += 1
  63.            Else
  64.                If (ch3 = "."c) Then
  65.                    num4 += 1
  66.                    If flag Then
  67.                        Exit Do
  68.                    End If
  69.                    flag = True
  70.                    num3 = num
  71.                    Continue Do
  72.                End If
  73.                If (((ch3 = "e"c) OrElse (ch3 = "E"c)) OrElse ((ch3 = "d"c) OrElse (ch3 = "D"c))) Then
  74.                    flag2 = True
  75.                    num4 += 1
  76.                End If
  77.                Exit Do
  78.            End If
  79.        End If
  80.    Loop
  81.    If flag Then
  82.        num2 = (num - num3)
  83.    End If
  84.    If Not flag2 Then
  85.        If (flag AndAlso (num2 <> 0)) Then
  86.            num8 = (num8 / Math.Pow(10, CDbl(num2)))
  87.        End If
  88.    Else
  89.        Dim flag4 As Boolean = False
  90.        Dim flag5 As Boolean = False
  91.        Do While (num4 < length)
  92.            ch = InputStr.Chars(num4)
  93.            Dim ch4 As Char = ch
  94.            If (((ch4 = ChrW(9)) OrElse (ch4 = ChrW(10))) OrElse (((ch4 = ChrW(13)) OrElse (ch4 = " "c)) OrElse (ch4 = ChrW(12288)))) Then
  95.                num4 += 1
  96.            ElseIf ((ch4 >= "0"c) AndAlso (ch4 <= "9"c)) Then
  97.                y = (((y * 10) + CDbl(ch)) - 48)
  98.                num4 += 1
  99.            Else
  100.                If (ch4 = "+"c) Then
  101.                    If flag4 Then
  102.                        Exit Do
  103.                    End If
  104.                    flag4 = True
  105.                    num4 += 1
  106.                    Continue Do
  107.                End If
  108.                If ((ch4 <> "-"c) OrElse flag4) Then
  109.                    Exit Do
  110.                End If
  111.                flag4 = True
  112.                flag5 = True
  113.                num4 += 1
  114.            End If
  115.        Loop
  116.        If flag5 Then
  117.            y = (y + num2)
  118.            num8 = (num8 * Math.Pow(10, -y))
  119.        Else
  120.            y = (y - num2)
  121.            num8 = (num8 * Math.Pow(10, y))
  122.        End If
  123.    End If
  124.    If Double.IsInfinity(num8) Then
  125.        Throw ExceptionUtils.VbMakeException(6)
  126.    End If
  127.    If flag3 Then
  128.        num8 = -num8
  129.    End If
  130.    Select Case ch
  131.        Case "%"c
  132.            If (num2 > 0) Then
  133.                Throw ExceptionUtils.VbMakeException(13)
  134.            End If
  135.            Return CDbl(CShort(Math.Round(num8)))
  136.        Case "&"c
  137.            If (num2 > 0) Then
  138.                Throw ExceptionUtils.VbMakeException(13)
  139.            End If
  140.            Return CDbl(CInt(Math.Round(num8)))
  141.        Case "!"c
  142.            Return CDbl(CSng(num8))
  143.        Case "@"c
  144.            Return Convert.ToDouble(New Decimal(num8))
  145.    End Select
  146.    Return num8
  147. End Function
  148.  

Y estas son las de la función "IsNumeric" del mismo namespace:
Código
  1. Public Shared Function IsNumeric(ByVal expression As Object) As Boolean
  2.    Dim num As Double
  3.    Dim convertible As IConvertible = TryCast(expression,IConvertible)
  4.    If (convertible Is Nothing) Then
  5.        Dim chArray As Char() = TryCast(expression,Char())
  6.        If (chArray Is Nothing) Then
  7.            Return False
  8.        End If
  9.        expression = New String(chArray)
  10.    End If
  11.    Dim typeCode As TypeCode = convertible.GetTypeCode
  12.    If ((typeCode <> TypeCode.String) AndAlso (typeCode <> TypeCode.Char)) Then
  13.        Return Information.IsOldNumericTypeCode(typeCode)
  14.    End If
  15.    Dim str As String = convertible.ToString(Nothing)
  16.    Try
  17.        Dim num2 As Long
  18.        If Utils.IsHexOrOctValue(str, num2) Then
  19.            Return True
  20.        End If
  21.    Catch exception As StackOverflowException
  22.        Throw exception
  23.    Catch exception2 As OutOfMemoryException
  24.        Throw exception2
  25.    Catch exception3 As ThreadAbortException
  26.        Throw exception3
  27.    Catch exception6 As Exception
  28.        Return False
  29.    End Try
  30.    Return DoubleType.TryParse(str, num)
  31. End Function
  32.  
  33. Friend Shared Function IsHexOrOctValue(ByVal Value As String, ByRef i64Value As Long) As Boolean
  34.    Dim num As Integer
  35.    Dim length As Integer = Value.Length
  36.    Do While (num < length)
  37.        Dim ch As Char = Value.Chars(num)
  38.        If ((ch = "&"c) AndAlso ((num + 2) < length)) Then
  39.            ch = Char.ToLower(Value.Chars((num + 1)), CultureInfo.InvariantCulture)
  40.            Dim str As String = Utils.ToHalfwidthNumbers(Value.Substring((num + 2)), Utils.GetCultureInfo)
  41.            Select Case ch
  42.                Case "h"c
  43.                    i64Value = Convert.ToInt64(str, &H10)
  44.                    goto Label_0087
  45.                Case "o"c
  46.                    i64Value = Convert.ToInt64(str, 8)
  47.                    goto Label_0087
  48.            End Select
  49.            Throw New FormatException
  50.        End If
  51.        If ((ch <> " "c) AndAlso (ch <> ChrW(12288))) Then
  52.            Return False
  53.        End If
  54.        num += 1
  55.    Loop
  56.    Return False
  57. Label_0087:
  58.    Return True
  59. End Function
  60.  


Mientras que esto son las instrucciones de la función "Double.TryParse" dentro del namespace System:

Código
  1. <__DynamicallyInvokable> _
  2. Public Shared Function TryParse(ByVal s As String, <Out> ByRef result As Double) As Boolean
  3.    Return Double.TryParse(s, (NumberStyles.Float Or NumberStyles.AllowThousands), NumberFormatInfo.CurrentInfo, result)
  4. End Function
  5.  
  6. Private Shared Function TryParse(ByVal s As String, ByVal style As NumberStyles, ByVal info As NumberFormatInfo, <Out> ByRef result As Double) As Boolean
  7.    If (s Is Nothing) Then
  8.        result = 0
  9.        Return False
  10.    End If
  11.    If Not Number.TryParseDouble(s, style, info, result) Then
  12.        Dim str As String = s.Trim
  13.        If Not str.Equals(info.PositiveInfinitySymbol) Then
  14.            If Not str.Equals(info.NegativeInfinitySymbol) Then
  15.                If Not str.Equals(info.NaNSymbol) Then
  16.                    Return False
  17.                End If
  18.                result = Double.NaN
  19.            Else
  20.                result = Double.NegativeInfinity
  21.            End If
  22.        Else
  23.            result = Double.PositiveInfinity
  24.        End If
  25.    End If
  26.    Return True
  27. End Function
  28.  
  29. <SecuritySafeCritical> _
  30. Friend Shared Function TryParseDouble(ByVal value As String, ByVal options As NumberStyles, ByVal numfmt As NumberFormatInfo, <Out> ByRef result As Double) As Boolean
  31.    Dim stackBuffer As Byte* = stackalloc Byte[DirectCast(NumberBuffer.NumberBufferBytes, IntPtr)]
  32.    Dim number As New NumberBuffer(stackBuffer)
  33.    result = 0
  34.    If Not Number.TryStringToNumber(value, options, number, numfmt, False) Then
  35.        Return False
  36.    End If
  37.    If Not Number.NumberBufferToDouble(number.PackForNative, result) Then
  38.        Return False
  39.    End If
  40.    Return True
  41. End Function
  42.  
  43. <TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")> _
  44. Friend Shared Function TryStringToNumber(ByVal str As String, ByVal options As NumberStyles, ByRef number As NumberBuffer, ByVal numfmt As NumberFormatInfo, ByVal parseDecimal As Boolean) As Boolean
  45.    Return Number.TryStringToNumber(str, options, number, Nothing, numfmt, parseDecimal)
  46. End Function
  47.  
  48. <SecuritySafeCritical, FriendAccessAllowed> _
  49. Friend Shared Function TryStringToNumber(ByVal str As String, ByVal options As NumberStyles, ByRef number As NumberBuffer, ByVal sb As StringBuilder, ByVal numfmt As NumberFormatInfo, ByVal parseDecimal As Boolean) As Boolean
  50.    If (str Is Nothing) Then
  51.        Return False
  52.    End If
  53.    Dim str2 As Char*
  54.    Fixed str2 = DirectCast(str, Char*)
  55.        Dim chPtr As Char* = str2
  56.        Dim chPtr2 As Char* = chPtr
  57.        If (Not Number.ParseNumber(chPtr2, options, number, sb, numfmt, parseDecimal) OrElse ((CLng(((chPtr2 - chPtr) / 2)) < str.Length) AndAlso Not Number.TrailingZeros(str, CInt(CLng(((chPtr2 - chPtr) / 2)))))) Then
  58.            Return False
  59.        End If
  60.    End Fixed
  61.    Return True
  62. End Function
  63.  
  64. <SecurityCritical> _
  65. Private Shared Function ParseNumber(ByRef str As Char*, ByVal options As NumberStyles, ByRef number As NumberBuffer, ByVal sb As StringBuilder, ByVal numfmt As NumberFormatInfo, ByVal parseDecimal As Boolean) As Boolean
  66.    Dim currencyDecimalSeparator As String
  67.    Dim currencyGroupSeparator As String
  68.    Dim chPtr2 As Char*
  69.    number.scale = 0
  70.    number.sign = False
  71.    Dim currencySymbol As String = Nothing
  72.    Dim ansiCurrencySymbol As String = Nothing
  73.    Dim numberDecimalSeparator As String = Nothing
  74.    Dim numberGroupSeparator As String = Nothing
  75.    Dim flag As Boolean = False
  76.    If ((options And NumberStyles.AllowCurrencySymbol) <> NumberStyles.None) Then
  77.        currencySymbol = numfmt.CurrencySymbol
  78.        If (Not numfmt.ansiCurrencySymbol Is Nothing) Then
  79.            ansiCurrencySymbol = numfmt.ansiCurrencySymbol
  80.        End If
  81.        numberDecimalSeparator = numfmt.NumberDecimalSeparator
  82.        numberGroupSeparator = numfmt.NumberGroupSeparator
  83.        currencyDecimalSeparator = numfmt.CurrencyDecimalSeparator
  84.        currencyGroupSeparator = numfmt.CurrencyGroupSeparator
  85.        flag = True
  86.    Else
  87.        currencyDecimalSeparator = numfmt.NumberDecimalSeparator
  88.        currencyGroupSeparator = numfmt.NumberGroupSeparator
  89.    End If
  90.    Dim num As Integer = 0
  91.    Dim flag2 As Boolean = False
  92.    Dim flag3 As Boolean = (Not sb Is Nothing)
  93.    Dim flag4 As Boolean = (flag3 AndAlso ((options And NumberStyles.AllowHexSpecifier) <> NumberStyles.None))
  94.    Dim num2 As Integer = If(flag3, &H7FFFFFFF, 50)
  95.    Dim p As Char* = str
  96.    Dim ch As Char = p(0)
  97.    Do While True
  98.        If ((Not Number.IsWhite(ch) OrElse ((options And NumberStyles.AllowLeadingWhite) = NumberStyles.None)) OrElse (((num And 1) <> 0) AndAlso (((num And 1) = 0) OrElse (((num And &H20) = 0) AndAlso (numfmt.numberNegativePattern <> 2))))) Then
  99.            If (flag2 = (((options And NumberStyles.AllowLeadingSign) <> NumberStyles.None) AndAlso ((num And 1) = 0)) AndAlso (Not chPtr2 = Number.MatchChars(p, numfmt.positiveSign) Is Nothing)) Then
  100.                num = (num Or 1)
  101.                p = (chPtr2 - 1)
  102.            ElseIf (flag2 AndAlso (Not chPtr2 = Number.MatchChars(p, numfmt.negativeSign) Is Nothing)) Then
  103.                num = (num Or 1)
  104.                number.sign = True
  105.                p = (chPtr2 - 1)
  106.            ElseIf (((ch = "("c) AndAlso ((options And NumberStyles.AllowParentheses) <> NumberStyles.None)) AndAlso ((num And 1) = 0)) Then
  107.                num = (num Or 3)
  108.                number.sign = True
  109.            Else
  110.                If (((currencySymbol Is Nothing) OrElse (chPtr2 = Number.MatchChars(p, currencySymbol) Is Nothing)) AndAlso ((ansiCurrencySymbol Is Nothing) OrElse (chPtr2 = Number.MatchChars(p, ansiCurrencySymbol) Is Nothing))) Then
  111.                    Exit Do
  112.                End If
  113.                num = (num Or &H20)
  114.                currencySymbol = Nothing
  115.                ansiCurrencySymbol = Nothing
  116.                p = (chPtr2 - 1)
  117.            End If
  118.        End If
  119.        ch = ++p
  120.    Loop
  121.    Dim num3 As Integer = 0
  122.    Dim index As Integer = 0
  123.    Do While True
  124.        If (((ch >= "0"c) AndAlso (ch <= "9"c)) OrElse (((options And NumberStyles.AllowHexSpecifier) <> NumberStyles.None) AndAlso (((ch >= "a"c) AndAlso (ch <= "f"c)) OrElse ((ch >= "A"c) AndAlso (ch <= "F"c))))) Then
  125.            num = (num Or 4)
  126.            If (((ch <> "0"c) OrElse ((num And 8) <> 0)) OrElse flag4) Then
  127.                If (num3 < num2) Then
  128.                    If flag3 Then
  129.                        sb.Append(ch)
  130.                    Else
  131.                        number.digits(num3++) = ch
  132.                    End If
  133.                    If ((ch <> "0"c) OrElse parseDecimal) Then
  134.                        index = num3
  135.                    End If
  136.                End If
  137.                If ((num And &H10) = 0) Then
  138.                    number.scale += 1
  139.                End If
  140.                num = (num Or 8)
  141.            ElseIf ((num And &H10) <> 0) Then
  142.                number.scale -= 1
  143.            End If
  144.        ElseIf ((((options And NumberStyles.AllowDecimalPoint) <> NumberStyles.None) AndAlso ((num And &H10) = 0)) AndAlso ((Not chPtr2 = Number.MatchChars(p, currencyDecimalSeparator) Is Nothing) OrElse ((flag AndAlso ((num And &H20) = 0)) AndAlso (Not chPtr2 = Number.MatchChars(p, numberDecimalSeparator) Is Nothing)))) Then
  145.            num = (num Or &H10)
  146.            p = (chPtr2 - 1)
  147.        Else
  148.            If (((((options And NumberStyles.AllowThousands) = NumberStyles.None) OrElse ((num And 4) = 0)) OrElse ((num And &H10) <> 0)) OrElse ((chPtr2 = Number.MatchChars(p, currencyGroupSeparator) Is Nothing) AndAlso ((Not flag OrElse ((num And &H20) <> 0)) OrElse (chPtr2 = Number.MatchChars(p, numberGroupSeparator) Is Nothing)))) Then
  149.                Exit Do
  150.            End If
  151.            p = (chPtr2 - 1)
  152.        End If
  153.        ch = ++p
  154.    Loop
  155.    Dim flag5 As Boolean = False
  156.    number.precision = index
  157.    If flag3 Then
  158.        sb.Append(ChrW(0))
  159.    Else
  160.        number.digits(index) = ChrW(0)
  161.    End If
  162.    If ((num And 4) <> 0) Then
  163.        If (((ch = "E"c) OrElse (ch = "e"c)) AndAlso ((options And NumberStyles.AllowExponent) <> NumberStyles.None)) Then
  164.            Dim chPtr3 As Char* = p
  165.            ch = ++p
  166.            chPtr2 = Number.MatchChars(p, numfmt.positiveSign)
  167.            If (Not chPtr2 Is Nothing) Then
  168.                ch = p = chPtr2
  169.            Else
  170.                chPtr2 = Number.MatchChars(p, numfmt.negativeSign)
  171.                If (Not chPtr2 Is Nothing) Then
  172.                    ch = p = chPtr2
  173.                    flag5 = True
  174.                End If
  175.            End If
  176.            If ((ch >= "0"c) AndAlso (ch <= "9"c)) Then
  177.                Dim num5 As Integer = 0
  178.                Do
  179.                    num5 = ((num5 * 10) + (ch - "0"c))
  180.                    ch = ++p
  181.                    If (num5 > &H3E8) Then
  182.                        num5 = &H270F
  183.                        Do While ((ch >= "0"c) AndAlso (ch <= "9"c))
  184.                            ch = ++p
  185.                        Loop
  186.                    End If
  187.                Loop While ((ch >= "0"c) AndAlso (ch <= "9"c))
  188.                If flag5 Then
  189.                    num5 = -num5
  190.                End If
  191.                number.scale = (number.scale + num5)
  192.            Else
  193.                p = chPtr3
  194.                ch = p(0)
  195.            End If
  196.        End If
  197.        Do While True
  198.            If (Not Number.IsWhite(ch) OrElse ((options And NumberStyles.AllowTrailingWhite) = NumberStyles.None)) Then
  199.                If (flag2 = (((options And NumberStyles.AllowTrailingSign) <> NumberStyles.None) AndAlso ((num And 1) = 0)) AndAlso (Not chPtr2 = Number.MatchChars(p, numfmt.positiveSign) Is Nothing)) Then
  200.                    num = (num Or 1)
  201.                    p = (chPtr2 - 1)
  202.                ElseIf (flag2 AndAlso (Not chPtr2 = Number.MatchChars(p, numfmt.negativeSign) Is Nothing)) Then
  203.                    num = (num Or 1)
  204.                    number.sign = True
  205.                    p = (chPtr2 - 1)
  206.                ElseIf ((ch = ")"c) AndAlso ((num And 2) <> 0)) Then
  207.                    num = (num And -3)
  208.                Else
  209.                    If (((currencySymbol Is Nothing) OrElse (chPtr2 = Number.MatchChars(p, currencySymbol) Is Nothing)) AndAlso ((ansiCurrencySymbol Is Nothing) OrElse (chPtr2 = Number.MatchChars(p, ansiCurrencySymbol) Is Nothing))) Then
  210.                        Exit Do
  211.                    End If
  212.                    currencySymbol = Nothing
  213.                    ansiCurrencySymbol = Nothing
  214.                    p = (chPtr2 - 1)
  215.                End If
  216.            End If
  217.            ch = ++p
  218.        Loop
  219.        If ((num And 2) = 0) Then
  220.            If ((num And 8) = 0) Then
  221.                If Not parseDecimal Then
  222.                    number.scale = 0
  223.                End If
  224.                If ((num And &H10) = 0) Then
  225.                    number.sign = False
  226.                End If
  227.            End If
  228.            str = p
  229.            Return True
  230.        End If
  231.    End If
  232.    str = p
  233.    Return False
  234. End Function
  235.  

Espero que se pueda entender la diferencia, y lo que denomino robustez ...aparte de lo que ya he comentado sobre ello.

Doy este debate por finalizado para no desviar todavía más el tema principal.

Saludos!
« Última modificación: 6 Febrero 2015, 11:36 am por Eleкtro » En línea

__Alvaro 2015__

Desconectado Desconectado

Mensajes: 164



Ver Perfil WWW
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #7 en: 6 Febrero 2015, 17:21 pm »

Hola,

Citar
Espero que se pueda entender la diferencia, y lo que denomino robustez ...aparte de lo que ya he comentado sobre ello.

Si es mas robusto, pero también es mucho mas pesado, y gracias a esa metodología de no optimizar mas en en velocidad y ahorro de código, las plataformas Windows se han vuelto toscas, lentas y evidentemente sobrecargadas, por ello Linux gana mas y mas usuarios día a día.

Acordaremos no estar de acuerdo, en todo, así no se hace spam.

Saludos.
« Última modificación: 6 Febrero 2015, 17:25 pm por __Alvaro 2015__ » En línea

"Pasión por la programación"
nevachana

Desconectado Desconectado

Mensajes: 61


Ver Perfil
Re: [Ayuda] Como hacer para validar una text box para q admita solo numeros
« Respuesta #8 en: 6 Febrero 2015, 17:27 pm »

No sé en que lenguaje estás pero es muy sencillo ^^
creas una lista con los caracteres no deseados:
Código
  1.    public static List<string> blocked = new List<string>
  2.        {
  3.            "a",
  4.            "b",
  5.            "c"
  6.        };
después en el botón donde hagas la acción añades una condicional.
Código
  1.    if(blocked.Contains(textBox1.Text))
  2.              MessageBox.Show("Caracter no válido");
  3.          else
  4.              MessageBox.Show("Caracter válido");
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Validar solo números en un INT en C++
Programación C/C++
RGT 1 6,313 Último mensaje 5 Noviembre 2015, 12:31 pm
por class_OpenGL
Script cmd para extraer solo números en un texto.
Scripting
lizana16288 3 4,656 Último mensaje 30 Abril 2016, 13:55 pm
por Eleкtro
Ayuda para hacer un subprogama
Programación C/C++
Juleen26 3 1,952 Último mensaje 11 Junio 2016, 21:00 pm
por Juleen26
Así es como Egipto no solo censuró Internet, sino que aprovechó para hacer ...
Noticias
wolfbcn 0 934 Último mensaje 4 Julio 2018, 02:02 am
por wolfbcn
SOLO VALIDAR ENTRADA DE NUMEROS
Programación C/C++
WarrirorPT3 1 2,177 Último mensaje 15 Abril 2019, 23:28 pm
por K-YreX
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines