locked
limit textbox input to numbers and range of numbers RRS feed

  • Question

  • hello all again. i have one more issues, and hope is the last for now. How can I limit a textboxe's input to only numerical with certain range of values (eg -10 to 10) and with that happening while I type in the values?
    • Moved by lucy-liu Friday, April 6, 2012 8:45 AM it is a vb issue (From:Visual Studio Editor)
    Wednesday, April 4, 2012 9:12 PM

Answers

  • Hello,

    Have you considered a NumericUpDown control? You can set min and max values and has up/down arrows to allow the user to not only add values from typing a value in but via the up/down arrows. If you don't like the up/down arrows they can be removed as shown in the custom control below.

    Imports System.Drawing
    Imports System.Windows.Forms
    ''' <summary>
    ''' Basically this control loses the spinners for incrementing
    ''' the control's value property and adds logic to handle key
    ''' down and key up to change this control's value honoring the
    ''' Minimum and Maximum value of this control.
    ''' </summary>
    ''' <remarks></remarks>
    <ToolboxBitmap(GetType(NumericUpDown))> _
    Public Class NumericEditBox
        Inherits System.Windows.Forms.NumericUpDown
        Public Sub New()
            MyBase.New()
            ' hide up/down control
            Controls(0).Visible = False
        End Sub
        Protected Overrides Sub OnTextBoxResize( _
            ByVal source As Object, ByVal e As System.EventArgs)
            ' without this code the up/down control still shows
            Controls(0).Size = New Size(0, ClientSize.Height)
            Controls(1).Size = New Size(ClientSize.Width, ClientSize.Height)
        End Sub
        Private Sub NumericEditBox_KeyDown( _
            ByVal sender As Object, _
            ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
            Dim CurrentValue As Decimal = Value
            If e.KeyCode = Keys.Subtract Then
                Dim AllowMinus As Boolean = Minimum < 0
                If (CurrentValue - Increment) >= Minimum Then
                    If Not AllowMinus Then
                        Dim TB As TextBox = DirectCast(Controls(1), TextBox)
                        TB.Text = TB.Text.Replace("-", "")
                        TB.Update()
                    End If
                    Value = CurrentValue - Increment
                End If
                e.SuppressKeyPress = True
            ElseIf e.KeyCode = Keys.Add Then
                If (CurrentValue + Increment) <= Maximum Then
                    Value = CurrentValue + Increment
                End If
                e.SuppressKeyPress = True
            End If
        End Sub
    End Class


    KSG

    • Proposed as answer by Rudedog2 Friday, April 6, 2012 2:01 PM
    • Marked as answer by Mark Liu-lxf Thursday, April 12, 2012 7:27 AM
    Friday, April 6, 2012 12:27 PM
  • You can try this simple code:

    Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
    	If e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> "-"C Then
    		'allow backspace for deleting and minus simbol
    		e.Handled = Not Char.IsNumber(e.KeyChar)
    		'allow numbers only
    		If Not e.Handled Then
    			Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(textBox1.Text = String.Empty, "", textBox1.Text), e.KeyChar.ToString()))
    			If num < -10 OrElse num > 10 Then
    				e.Handled = True
    			End If
    		End If
    	End If
    End Sub

    It works, tested.

    bye


    Mitja

    • Marked as answer by Mark Liu-lxf Thursday, April 12, 2012 7:27 AM
    Friday, April 6, 2012 1:13 PM
  • Hi johnkaragk,

    Welcome to the MSDN forum.

    Instead of using Textchanged event and KeyPress event, I will suggest you to use leave event of textbox. It will check the number when the focus leaves the textbox. Here is a sample:

     Private Sub TextBox1_Leave(sender As System.Object, e As System.EventArgs) Handles TextBox1.Leave
            If Convert.ToDecimal(TextBox1.Text) < -10 OrElse Convert.ToDecimal(TextBox1.Text) > 10 Then
                MessageBox.Show("Valid Decimal Data: -10~10")
            End If
        End Sub

    Hope this helps.


    Mark Liu-lxf [MSFT]
    MSDN Community Support | Feedback to us


    • Edited by Mark Liu-lxf Friday, April 6, 2012 9:08 AM
    • Marked as answer by Mark Liu-lxf Thursday, April 12, 2012 7:28 AM
    Friday, April 6, 2012 8:54 AM

All replies

  • Thursday, April 5, 2012 7:31 AM
  • Thanx Purvi for ur answer. however the one you sent me is in C#. I am writing my program in VB in which im kind of a rookie!
    Thursday, April 5, 2012 8:17 AM
  • Hi,

    you use online C# to VB Converter to convert Purvi Code.

    i converted sample code below

    Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
    	If Not Char.IsNumber(e.KeyChar) Then
    		e.Handled = True
    	End If
    End Sub
    
    
    Private Sub textBox1_TextChanged(sender As Object, e As EventArgs)
    	If Convert.ToDecimal(textBox1.Text) < 0 OrElse Convert.ToDecimal(textBox1.Text) > 60 Then
    		MessageBox.Show("Valid Decimal Data: 0~60")
    	End If
    End Sub

    Hope this help to you

    Kalpesh


    Please "Mark as Answer" if this post answered your question. :)

    Kalpesh Chhatrala | Software Developer | Rajkot | India

    Kalpesh 's Blog

    VFP Form to C#, Vb.Net Conversion Utility

    Thursday, April 5, 2012 9:03 AM
  • Thank you Kalpesh that was helpful. I only have two problems. I cannot enter values less than 0 and the backspace is not working at all. Is there a way to fix that?
    • Edited by johnkaragk Thursday, April 5, 2012 9:17 AM
    Thursday, April 5, 2012 9:13 AM
  • Hi johnkaragk,

    This is not a Visual Studio Editor issue, I will move it to "Visual Basic General" forum for a better support.

    Thank you for your understanding!


    Lucy Liu [MSFT]
    MSDN Community Support | Feedback to us

    Friday, April 6, 2012 8:45 AM
  • Hi johnkaragk,

    Welcome to the MSDN forum.

    Instead of using Textchanged event and KeyPress event, I will suggest you to use leave event of textbox. It will check the number when the focus leaves the textbox. Here is a sample:

     Private Sub TextBox1_Leave(sender As System.Object, e As System.EventArgs) Handles TextBox1.Leave
            If Convert.ToDecimal(TextBox1.Text) < -10 OrElse Convert.ToDecimal(TextBox1.Text) > 10 Then
                MessageBox.Show("Valid Decimal Data: -10~10")
            End If
        End Sub

    Hope this helps.


    Mark Liu-lxf [MSFT]
    MSDN Community Support | Feedback to us


    • Edited by Mark Liu-lxf Friday, April 6, 2012 9:08 AM
    • Marked as answer by Mark Liu-lxf Thursday, April 12, 2012 7:28 AM
    Friday, April 6, 2012 8:54 AM
  • Hello,

    Have you considered a NumericUpDown control? You can set min and max values and has up/down arrows to allow the user to not only add values from typing a value in but via the up/down arrows. If you don't like the up/down arrows they can be removed as shown in the custom control below.

    Imports System.Drawing
    Imports System.Windows.Forms
    ''' <summary>
    ''' Basically this control loses the spinners for incrementing
    ''' the control's value property and adds logic to handle key
    ''' down and key up to change this control's value honoring the
    ''' Minimum and Maximum value of this control.
    ''' </summary>
    ''' <remarks></remarks>
    <ToolboxBitmap(GetType(NumericUpDown))> _
    Public Class NumericEditBox
        Inherits System.Windows.Forms.NumericUpDown
        Public Sub New()
            MyBase.New()
            ' hide up/down control
            Controls(0).Visible = False
        End Sub
        Protected Overrides Sub OnTextBoxResize( _
            ByVal source As Object, ByVal e As System.EventArgs)
            ' without this code the up/down control still shows
            Controls(0).Size = New Size(0, ClientSize.Height)
            Controls(1).Size = New Size(ClientSize.Width, ClientSize.Height)
        End Sub
        Private Sub NumericEditBox_KeyDown( _
            ByVal sender As Object, _
            ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
            Dim CurrentValue As Decimal = Value
            If e.KeyCode = Keys.Subtract Then
                Dim AllowMinus As Boolean = Minimum < 0
                If (CurrentValue - Increment) >= Minimum Then
                    If Not AllowMinus Then
                        Dim TB As TextBox = DirectCast(Controls(1), TextBox)
                        TB.Text = TB.Text.Replace("-", "")
                        TB.Update()
                    End If
                    Value = CurrentValue - Increment
                End If
                e.SuppressKeyPress = True
            ElseIf e.KeyCode = Keys.Add Then
                If (CurrentValue + Increment) <= Maximum Then
                    Value = CurrentValue + Increment
                End If
                e.SuppressKeyPress = True
            End If
        End Sub
    End Class


    KSG

    • Proposed as answer by Rudedog2 Friday, April 6, 2012 2:01 PM
    • Marked as answer by Mark Liu-lxf Thursday, April 12, 2012 7:27 AM
    Friday, April 6, 2012 12:27 PM
  • You can try this simple code:

    Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
    	If e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> "-"C Then
    		'allow backspace for deleting and minus simbol
    		e.Handled = Not Char.IsNumber(e.KeyChar)
    		'allow numbers only
    		If Not e.Handled Then
    			Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(textBox1.Text = String.Empty, "", textBox1.Text), e.KeyChar.ToString()))
    			If num < -10 OrElse num > 10 Then
    				e.Handled = True
    			End If
    		End If
    	End If
    End Sub

    It works, tested.

    bye


    Mitja

    • Marked as answer by Mark Liu-lxf Thursday, April 12, 2012 7:27 AM
    Friday, April 6, 2012 1:13 PM
  • I think the best approach is to create a custom control by inheriting from a TextBox or NumericUpDown.  Don't clutter up your Form class with code that does not directly apply with managing the behavior of form instance.  This is known as "Separation of Concerns" in Object Oriented Programming.   The numeric-only behavior is a behavior that is exclusive to the control.  The Form instance should manage user interaction with the controls and manage the interaction between controls.  The Form class should not contain code that alters the behaviors of controls.  Use separate classes to define behaviors. 

    The code posted by Mitja could be included with a slight modification into a custom class that inherits TextBox.

    Hope this helps. 

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/

    Friday, April 6, 2012 2:08 PM