简体   繁体   中英

Putting value from Combobox Item to Textbox in vb.net “Conversion from string ”“ to type 'Double' is not valid.”

Public Class Main
    Dim Adult As Integer = 495 'Adult as Integer
    Dim Senior As Integer = 395 'Senior as Integer

    Private Sub Combo() 'New created Sub
        Dim Aval = Combad.Text 'Aval as Combo box Adult
        Dim Sval = Comse.Text 'Sval as Combo box Senior


        Textpay.Text = Adult * Aval + Senior * Sval 'Adding up the total of both Combo Box's Value
    End Sub
Private Sub Combad_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Combad.SelectedIndexChanged
        Combo() 'Private Sub
    End Sub

    Private Sub Comse_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Comse.SelectedIndexChanged
        Combo() 'Private Sub
    End Sub
End Class

First check if your combobox is empty or not cause you will get an error if it is (by using if Aval <> string.empty ) second of all you need to check if the combobox is a number, you can use If Integer.TryParse(Aval, Nothing) . Use AndAlso if you want to check both at the same time if Aval <> string.empty AndAlso Integer.TryParse(Aval, Nothing)

You parse the String values in the.Text property with.TryParse. The method will return True and assign the Integer value to the provided variable if the conversion is possible.

    Private Adult As Integer = 495
    Private Senior As Integer = 395

    Private Sub Combo()
        Dim Aval As Integer
        Dim Sval As Integer
        If Integer.TryParse(Combad.Text, Aval) AndAlso Integer.TryParse(Comse.Text, Sval) Then
            Textpay.Text = (Adult * Aval + Senior * Sval).ToString
        Else
            MessageBox.Show("Both drop down boxes must display a number.")
        End If
    End Sub

EDIT

Here is the complete code that I just tested.

Private Adult As Integer = 495
Private Senior As Integer = 395


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ComboBox1.Items.AddRange({1, 2, 3, 4})
    ComboBox2.Items.AddRange({1, 2, 3, 4})
End Sub


Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    Combo()
End Sub

Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
    Combo()
End Sub

Private Sub Combo()
    Dim Aval As Integer
    Dim Sval As Integer
    If Integer.TryParse(ComboBox1.Text, Aval) AndAlso Integer.TryParse(ComboBox2.Text, Sval) Then
        TextBox1.Text = (Adult * Aval + Senior * Sval).ToString
    Else
        MessageBox.Show("Both drop down boxes must display a number.")
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM