none
Input String was not in a correct format RRS feed

  • Question

  • I am using the function below to test two variable, Maxvalue and Maxvaluee1. Maxvalue is an integer constant declared at the module level with a value of 100 while Maxvalue1 is an integer declared at the function level. The function runs well when Maxvalue is less or equal to 100, however if Maxvalue1 is > 100 the function runs fine too but on exit it will crash with the following information “Input string was not in the right format” with this part of the code highlighted “MaxValue1 = Integer.Parse(TextBox1.Text”

    Public Class Form1
        Private MaxValue As Integer
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            checkMax()
        End Sub
        Private Sub checkMax()
            Dim MaxValue1 As Integer
            MaxValue1 = Integer.Parse(TextBox1.Text)
            If MaxValue1 <= MaxValue Then
                TextBox1.Text = MaxValue1.ToString()
                TextBox1.BackColor = Color.White
                Label1.Text = " Value is" & MaxValue1
            Else
                MsgBox("Value can not be more than 100")
                Label1.Text = " Value is" & MaxValue1
                TextBox1.BackColor = Color.AntiqueWhite
                TextBox1.Clear()
                TextBox1.Select()
            End If
        End Sub
    End Class
    


    Sunday, June 11, 2017 11:58 AM

All replies

  • I am using the function below to test two variable, Maxvalue and Maxvaluee1. Maxvalue is an integer constant declared at the module level with a value of 100 while Maxvalue1 is an integer declared at the function level. The function runs well when Maxvalue is less or equal to 100, however if Maxvalue1 is > 100 the function runs fine too but on exit it will crash with the following information “Input string was not in the right format” with this part of the code highlighted “MaxValue1 = Integer.Parse(TextBox1.Text”

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click checkMax() End Sub Private Sub checkMax() Dim MaxValue1 As Integer MaxValue1 = Integer.Parse(TextBox1.Text) If MaxValue1 <= MaxValue Then TextBox1.Text = MaxValue1.ToString() TextBox1.BackColor = Color.White Label1.Text = " Value is" & MaxValue1 Else MsgBox("Value can not be more than 100") Label1.Text = " Value is" & MaxValue1 TextBox1.BackColor = Color.AntiqueWhite TextBox1.Clear() TextBox1.Select() End If End Sub

    alobi,

    That's difficult to read. Next time please use the code block tool to make it easier.

    What is your function supposed to do?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, June 11, 2017 12:25 PM
  • Hello,

    This is how you should convert from string to integer

    Dim MaxValue1 As Integer = 0
    If Integer.TryParse(TextBox1.Text, MaxValue1) Then
        MessageBox.Show($"{MaxValue1} is valid")
    Else
        MessageBox.Show($"{TextBox1.Text} is invalid, {MaxValue1} is still 0.")
    End If

    So you should have this

    Public Class Form1
        Private MaxValue As Integer = 89
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            checkMax()
        End Sub
        Private Sub checkMax()
            Dim MaxValue1 As Integer
            If Integer.TryParse(TextBox1.Text, MaxValue1) Then
                If MaxValue1 <= MaxValue Then
                    TextBox1.Text = MaxValue1.ToString()
                    TextBox1.BackColor = Color.White
                    Label1.Text = " Value is" & MaxValue1
                Else
                    MsgBox("Value can not be more than 100")
                    Label1.Text = " Value is" & MaxValue1
                    TextBox1.BackColor = Color.AntiqueWhite
                    TextBox1.Clear()
                    TextBox1.Select()
                End If
            End If
    
        End Sub
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Sunday, June 11, 2017 12:41 PM
    Moderator
  • The text contains something different from an integer, maybe a space, a alphabetic character of whatever. 

    Try the TryParse instead of that. 

    https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx


    Success
    Cor

    Sunday, June 11, 2017 12:42 PM
  • alobi,

    If you're trying to make sure that the user not only enters a valid integer but that the value meets criteria for minimum/maximum, one way you can do this is by using the .Validating event of the control (the control being a TextBox here).

    For example:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private ep As New ErrorProvider Private Const _minimum As Integer = 2 Private Const _maximum As Integer = 10 Private Sub _ Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load btn_ShowValue.Enabled = False End Sub Private Sub _ TextBox1_TextChanged(sender As System.Object, _ e As System.EventArgs) _ Handles TextBox1.TextChanged ep.Clear() If TextBox1.Text.Trim <> "" Then btn_ShowValue.Enabled = True Else btn_ShowValue.Enabled = False End If End Sub Private Sub _ TextBox1_Validating(sender As Object, _ e As System.ComponentModel.CancelEventArgs) _ Handles TextBox1.Validating If TextBox1.Text.Trim <> "" Then Dim sb As New System.Text.StringBuilder Dim tempInt As Integer If Integer.TryParse(TextBox1.Text, tempInt) Then ' .TryParse will cast the value to your variable - ' "tempInt" here, so now you can use that to test ' the min/max with: If tempInt < _minimum Then sb.AppendLine("The value must not be lower than") sb.AppendLine(String.Format("the minimum threshold of {0}.", _minimum)) sb.AppendLine() sb.AppendLine("Please re-enter the value") sb.AppendLine("or clear the text area completely") sb.AppendLine("in order to continue.") ep.SetError(TextBox1, sb.ToString) e.Cancel = True btn_ShowValue.Enabled = False ElseIf tempInt > _maximum Then sb.AppendLine("The value must not be higher than") sb.AppendLine(String.Format("the maximum threshold of {0}.", _maximum)) sb.AppendLine() sb.AppendLine("Please re-enter the value") sb.AppendLine("or clear the text area completely") sb.AppendLine("in order to continue.") ep.SetError(TextBox1, sb.ToString) e.Cancel = True btn_ShowValue.Enabled = False End If Else ' It's not a value which can be parsed as an ' integer. sb.AppendLine("The input value must be a") sb.AppendLine("whole number only.") sb.AppendLine() sb.AppendLine("Please re-enter the value") sb.AppendLine("or clear the text area completely") sb.AppendLine("in order to continue.") ep.SetError(TextBox1, sb.ToString) e.Cancel = True btn_ShowValue.Enabled = False End If End If End Sub Private Sub _ btn_ShowValue_Click(sender As System.Object, _ e As System.EventArgs) _ Handles btn_ShowValue.Click ' I can safely do this because the only way the ' code allowed it to get here was by passing ' through validation first -- otherwise the ' following would be dangerous: MessageBox.Show("Value: " & CInt(TextBox1.Text).ToString) End Sub End Class


    In the above I'm using an ErrorProvider that I declared in code but you can also just grab one from the toolbox and do the same thing.

    I'll explain how all of this works: When the user enters some text, when they leave that control, the .Validating event is raised. It now passes through whatever code you have there that checks it.

    In mine above, if the TextBox isn't empty then I have it testing that it's a valid whole number. If it's not, I set the ErrorProvider, but more importantly I tell it to cancel the event; the user can't leave the TextBox until they've corrected it.

    That's dangerous though: They can't even close the program now!

    To get around that, I give them an "out": Clear the text completely and it will ignore the .Validating event but notice also that if they clear the text, the button is then disabled so they can't proceed. Now it's safe:


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, June 11, 2017 1:34 PM
  • Here is another example where a custom TextBox provides the following.

    • Only accepts numerics (prohibits pasting from windows clipboard invalid values e.g. only 0-9 and.)
    • Provides properties to set min and max values (as integers)
    • Provides a property to see if current value is within the range of Min and Max.

    Create a new class, enter the following in.

    Imports System.ComponentModel
    Public Class numericTextbox
        Inherits TextBox
        <Category("Behavior")>
        <Description("Acceptable min value")>
        Public Property Min As Integer
        <Category("Behavior")>
        <Description("Acceptable max value")>
        Public Property Max As Integer
        Private mIsValid As Boolean
        <Browsable(False)>
        Public ReadOnly Property IsValid As Boolean
            Get
                Return IntegerValue.Between(Min, Max) AndAlso DoubleValue.Between(Min, Max)
            End Get
        End Property
    
        Const WM_PASTE As Integer = &H302
    
        <Browsable(False)>
        Public ReadOnly Property DoubleValue As Double
            Get
                If String.IsNullOrWhiteSpace(Text) Then
                    Return 0
                Else
                    Return CDbl(Text)
                End If
            End Get
        End Property
        <Browsable(False)>
        Public ReadOnly Property IntegerValue As Integer
            Get
                If String.IsNullOrWhiteSpace(Text) Then
                    Return 0
                Else
                    Return CInt(Text)
                End If
            End Get
        End Property
        Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
            Dim Value As String = Text
            Value = Value.Remove(SelectionStart, SelectionLength)
            Value = Value.Insert(SelectionStart, e.KeyChar)
            e.Handled = CBool(Value.LastIndexOf("-") > 0) Or
                Not (Char.IsControl(e.KeyChar) OrElse Char.IsDigit(e.KeyChar) OrElse
                     (e.KeyChar = "."c And
                      Not Text.Contains(".") Or e.KeyChar = "."c And
                      SelectedText.Contains(".")) OrElse (e.KeyChar = "-"c And
                                                             SelectionStart = 0))
    
            MyBase.OnKeyPress(e)
        End Sub
        Protected Overrides Sub WndProc(ByRef m As Message)
            If m.Msg = WM_PASTE Then
                Dim Value As String = Text
                Value = Value.Remove(SelectionStart, SelectionLength)
                Value = Value.Insert(SelectionStart, Clipboard.GetText)
                Dim result As Decimal = 0
                If Not Decimal.TryParse(Value, result) Then
                    Return
                End If
            End If
            MyBase.WndProc(m)
        End Sub
    End Class
    Public Module GenericExtensions
        <Runtime.CompilerServices.Extension>
        Public Function Between(Of T As IComparable(Of T))(ByVal actual As T, ByVal lower As T, ByVal upper As T) As Boolean
            Return actual.CompareTo(lower) >= 0 AndAlso actual.CompareTo(upper) < 0
        End Function
    End Module

    Place one of these TextBoxes on your form, include the following in Button1 Click event

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If NumericTextbox1.IsValid Then
            MessageBox.Show($"{NumericTextbox1.IntegerValue} is valid")
        Else
            MessageBox.Show($"{NumericTextbox1.Text} valid is between {NumericTextbox1.Min} and {NumericTextbox1.Max}")
        End If
    End Sub

    How to enhance, incorporate an Error Provider as introduced by Frank to eliminate the MessageBox is an option. 


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Proposed as answer by Frank L. Smith Sunday, June 11, 2017 4:21 PM
    • Marked as answer by alobi Sunday, June 11, 2017 4:37 PM
    • Unmarked as answer by alobi Sunday, June 11, 2017 4:42 PM
    Sunday, June 11, 2017 2:55 PM
    Moderator
  • Hi alobi,

    MaxValue1 = Integer.Parse(TextBox1.Text),This assumes that the value coming from the TextBox1.Text is convertable to an integer. If it's an string that can't be parsed, DbNull, etc. it will fail.

    So I agree with the Kareninstructor's opinion, you could need to detect whether the value of the TextBox1.Text is valid.

     Private Sub fun()
            Dim MaxValue As Integer = 0
            Dim MaxValue1 As Integer
            If MaxValue1 = Convert.ToInt32(TextBox1.Text) Then
                If MaxValue1 <= MaxValue Then
                    TextBox1.Text = MaxValue1.ToString()
                    TextBox1.BackColor = Color.White
                    Label1.Text = " Value is" & MaxValue1
                Else
                    MsgBox("Value can not be more than 100")
                    Label1.Text = " Value is" & MaxValue1
                    TextBox1.BackColor = Color.AntiqueWhite
                    TextBox1.Clear()
                    TextBox1.Select()
                End If
            Else
                MessageBox.Show("Textbox1.Text value is not valid")
    
            End If
        End Sub

    Best Regards,

    Cherry



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, June 12, 2017 2:54 AM
    Moderator