Hi,

I am having a problem with the if statement that I created in my code. The condition should be:

- Select Both Comboboxes (1&2) to print out a text in TextBox1

- If only One Combobox or No Combobox was selected, an error message appears and Nothing is printed in TextBox1.

The code I wrote did not function as I wanted. It prints out a text after I select Combobox1 which isn't the way it should be.
Please advise and thanks in advance.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If ComboBox1.SelectedIndex = -1 Then
            MessageBox.Show("You Should Select A Name & Age", "Error")
        ElseIf ComboBox2.SelectedIndex = -1 Then
            MessageBox.Show("You Should Select A Name & Age", "Error")
        TextBox1.Text = "Your Age"
        TextBox1.Text = TextBox1.Text & vbNewLine & "Your Name: " + ComboBox2.Text
        End If
    End Sub

Recommended Answers

All 3 Replies

As far as I know, ComboBox Indexes are 0 based.

So you might want to change your conditions to something like

If ComboBox1.SelectedIndex < 1 Then
            MessageBox.Show("You Should Select A Name & Age", "Error")
        ElseIf ComboBox2.SelectedIndex < 1 Then
            MessageBox.Show("You Should Select A Name & Age", "Error")
        TextBox1.Text = "Your Age"
        TextBox1.Text = TextBox1.Text & vbNewLine & "Your Name: " + ComboBox2.Text
        End If

actually this still wont work!

try something like

If (ComboBox1.SelectedIndex < 1) AndAlso (ComboBox2.SelectedIndex < 1) Then
   MessageBox.Show("You Should Select A Name & Age", "Error")
else
  TextBox1.Text = "Your Age"
  TextBox1.Text += ComboBox1.SelectedText & vbNewLine & "Your Name: " + ComboBox2.SelectedText
End If

Thank you so much, it worked.
I also tried this

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If ComboBox1.SelectedIndex = -1 Then
            MessageBox.Show("You Should Select A Name & Age", "Error")
        ElseIf ComboBox2.SelectedIndex = -1 Then
            MessageBox.Show("You Should Select A Name & Age", "Error")
        Else
        TextBox1.Text = "Your Age"
        TextBox1.Text = TextBox1.Text & vbNewLine & "Your Name: " + ComboBox2.Text
        End If
    End Sub

And it worked fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.