Search code examples
vb.netselectedlistboxitem

If statement for ListBox1.SelectedItem


I keep getting errors when i try and click an item on the listbox and then try and run the code. It tells me something about converting it to a boolean but i'm not entirely sure. I tried ToString() but to no luck.

I dont want the code to run unless something is selected inside of the Listbox.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If ListBox1.SelectedItem Then
        ProgressBar1.Value = 0
        Timer1.Start()
        Button1.Enabled = False

        System.Threading.Thread.Sleep(2000)
        TextBox1.Refresh()
        TextBox1.Text &= "Preparing"
        TextBox1.Refresh()
        System.Threading.Thread.Sleep(2000)
        TextBox1.Refresh()
        TextBox1.Text &= Environment.NewLine & ""
        TextBox1.Refresh()
        System.Threading.Thread.Sleep(2000)
        TextBox1.Text &= Environment.NewLine & ""

    Else
        MsgBox("", 0, "")
    End If
End Sub

Solution

  • ListBox.SelectedItem returns the actual selected item in the ListBox, but an If statement requires an expression to evaluate to a Boolean (true or false). What you're looking for is probably:

    If (ListBox.SelectedItems.Count > 0) Then