Search code examples
vb.netif-statementvariable-assignmentmessagebox

How can I ensure that a user does not leave any multiple choice inputs unselected?


I'm trying to do a hotel billing system wherein the user cannot leave combo boxes, radio buttons and list boxes not selected and i'm out of ideas can someone help me with this?

-newbie

Dim inp As Integer = 0

    If RadioButton1.Checked Or RadioButton2.Checked Or RadioButton3.Checked = False Then
        inp = 1
    End If
    If ComboBox1.Text = "" Then
        inp = 1
    End If
    If ListBox1.SelectedIndex() Then
        inp = 1
    End If
    If inp = 1 Then
        MessageBox.Show("No selected type of payment" & vbCrLf & "Or" & vbCrLf & "No selected room capacity" & vbCrLf & "Or" & vbCrLf & "No selected room type", "Error")
        inp = 0
    End If

Solution

  • You can do all of this in a single if statement, you just need to check each one against it's value.

    If (RadioButton1.Checked = False AndAlso RadioButton2.Checked = False AndAlso RadioButton3.Checked = False) OrElse Combobox1.SelectedIndex = -1 OrElse ListBox1.SelectedIndex = -1 Then
        MessageBox.Show("No selected type of payment" & vbCrLf & "Or" & vbCrLf & "No selected room capacity" & vbCrLf & "Or" & vbCrLf & "No selected room type", "Error")
    Exit Sub
    End If
    

    Using the OrElse will move on once any of the conditions are found to be true. If this happens, we can immediately move into the If block and display the message. At this point, there's no sense in continuing on with the rest of the routine, so we exit the sub, allowing the user to fix their missing information and try again.

    That being said, you have multiple problems in your original code. One is that your first line isn't doing what you think it's doing. (check each condition against it's value). Another is that you aren't checking the listbox's selectedindex against anything.

    Look up booleans as you could have used that instead of an int to handle your inp flag.

    you also have inp = inp = 1 which I think you wanted to subtract 1 from, either way, in this situation, you could have just set it back to 0 (see my boolean comment, it would handle this by allowing you to set it to true or false)

    Also, as a personal tip. If a user makes a mistake by not entering everything expected, please don't get into the habit of clearing all their work just to fix the issue. Your block of code tells the user that they messed up and then you go and set everything back to blank values.