locked
Testing whether a Multi-Select ListBox Item is selected RRS feed

  • Question

  • I'm converting one of my VB6 programs to VB.Net. I have a multi-select ListBox with many items. Seems the simple things give me the most trouble. I want to iterate through each item in the listbox and test whether it is selected. There are tons of listbox examples but I'm not finding the solution I'm looking for. Any assistance is appreciated.

    I'm using VS2015 VB.Net

    Dim i As Integer

    For i = 0 To ListBox.ItemsCount - 1

      If the item is selected Then

        Do something

      Else

      Do something else

      End if

    Next

    • Moved by Weiwei Cai Thursday, May 26, 2016 7:28 AM not Silverlight issue
    Wednesday, May 25, 2016 7:11 PM

Answers

  • Hi dw80916,

    You could have a look at below demo to check whether current item is selected or not.

        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            Dim i As Integer
    
            For i = 0 To ListBox1.Items.Count - 1
    
                If ListBox1.SelectedItems.Contains(ListBox1.Items(i).ToString()) Then
    
                    MessageBox.Show(ListBox1.Items(i).ToString())
    
                Else
                    'do somethings
                End If
    
            Next
        End Sub
    

    Best Regards,

    Albert Zhang

    Thursday, May 26, 2016 7:59 AM
  • I'm converting one of my VB6 programs to VB.Net. I have a multi-select ListBox with many items. Seems the simple things give me the most trouble. I want to iterate through each item in the listbox and test whether it is selected. There are tons of listbox examples but I'm not finding the solution I'm looking for. Any assistance is appreciated.

    I'm using VS2015 VB.Net

    Dim i As Integer

    For i = 0 To ListBox.ItemsCount - 1

      If the item is selected Then

        Do something

      Else

      Do something else

      End if

    Next

    I believe if the ListBox.SelectedItems count is greater than 0 then you can just iterate through that collection of selected items. I didn't test the code below though. Also it is recommended not to name an object with the same name used by an objects class I believe. So if you really named the ListBox "ListBox" then I would recommend altering the name to ListBox1 or something other than ListBox.

    If ListBox1.SelectedItems.Count > 0 Then

    ' Do something

    End If


    La vida loca

    Thursday, May 26, 2016 4:16 PM
  • DW,

    Maybe this will make it easier or, if not, at least more clear as to what's going on. I put a small class together that you can use so that you can know what's selected (and the text value of it along with the index of it) and what's not.

    The first point that I'd like to make is this: While it's typical that you'll use a ListBox with strings for the .Items collection, that's not what the control uses; it uses .Net objects (which can be anything, including a string). You'll see that when I cast to a string when I show the code, but first let me show you what I have here.

    A simple form with a ListBox (ListBox1) and a button (Button1):

    I populated the ListBox in code and since I know there are items in the .Items collection, I know it's ok to enable the button - but depending on how you're populating the ListBox, that might not be a safe assumption.

    As you can see, nothing is selected, but I'll click the button and see what it does (this will make more sense when you see the code):

    In the code, I have "Stop" which will work just like a breakpoint does; program execution will halt at that point and you can then hover your mouse over any variable which is then in scope and inspect its value.

    Hovering my mouse over the variable "data" above shows me this:

    There are two collections in the class which is returned to you: A collection of items which ARE selected and a collection of items which are NOT selected.

    Because they're collections, you need to expand each of them to see what they contain:

    As is not surprise here, the collection of selected items shows a length of zero so I'll look at the unselected collection:

    That shows there are three (again, no surprise). If I drill down one more level [each], you'll see the actual data:

    The other two are similar, obviously.

    Now I'll stop the program and restart it, this time selecting two of the items:

    When I click the button, the following shows what's returned from the class:

    The code for it is simpler than you might think:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load With ListBox1 .SelectionMode = SelectionMode.MultiExtended .Items.AddRange(New String() _ {"Apples", _ "Oranges", _ "Pears"}) End With End Sub Private Sub _ Button1_Click(sender As System.Object, _ e As System.EventArgs) _ Handles Button1.Click Dim data As New TextListBoxData(ListBox1) Stop End Sub End Class Public Class TextListBoxData Private _selectedItems As IEnumerable(Of TextListBoxItems) Private _unselectedItems As IEnumerable(Of TextListBoxItems) Public Sub New(ByVal lb As ListBox) Try If lb Is Nothing Then Throw New ArgumentNullException("ListBox Control", "Cannot be null." & vbCrLf) Else If lb.Items.Count > 0 Then Dim selected As New List(Of TextListBoxItems) Dim unselected As New List(Of TextListBoxItems) For i As Integer = 0 To lb.Items.Count - 1 Dim item As Object = lb.Items(i) If lb.SelectedItems.Contains(item) Then selected.Add(New TextListBoxItems(i, DirectCast(item, String))) Else unselected.Add(New TextListBoxItems(i, DirectCast(item, String))) End If Next _selectedItems = selected.ToArray _unselectedItems = unselected.ToArray End If End If Catch ex As Exception Throw End Try End Sub Public ReadOnly Property SelectedItems As IEnumerable(Of TextListBoxItems) Get Return _selectedItems End Get End Property Public ReadOnly Property UnselectedItems As IEnumerable(Of TextListBoxItems) Get Return _unselectedItems End Get End Property Public Class TextListBoxItems Private _index As Integer Private _text As String Friend Sub New(ByVal index As Integer, _ ByVal text As String) If Not String.IsNullOrWhiteSpace(text) AndAlso index >= 0 Then _index = index _text = text.Trim End If End Sub Public ReadOnly Property Index As Integer Get Return _index End Get End Property Public ReadOnly Property Text As String Get Return _text End Get End Property End Class End Class


    Whether you actually use this or not is up to you, but hopefully you'll try it at least once and step through the code - you'll gain insight as to what's what and then you won't need it again.

    :)


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Thursday, May 26, 2016 6:34 PM

All replies

  • Hi dw80916,

    This forum is discuss Silverlight .NET application problem.

    According to your description, your problem should be more related to VB code. I help you move this thread to VB forum for a better help. Thanks for your understanding.

    Best Regards,
    Weiwei


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, May 26, 2016 7:28 AM
  • Hi dw80916,

    You could have a look at below demo to check whether current item is selected or not.

        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            Dim i As Integer
    
            For i = 0 To ListBox1.Items.Count - 1
    
                If ListBox1.SelectedItems.Contains(ListBox1.Items(i).ToString()) Then
    
                    MessageBox.Show(ListBox1.Items(i).ToString())
    
                Else
                    'do somethings
                End If
    
            Next
        End Sub
    

    Best Regards,

    Albert Zhang

    Thursday, May 26, 2016 7:59 AM
  • I'm converting one of my VB6 programs to VB.Net. I have a multi-select ListBox with many items. Seems the simple things give me the most trouble. I want to iterate through each item in the listbox and test whether it is selected. There are tons of listbox examples but I'm not finding the solution I'm looking for. Any assistance is appreciated.

    I'm using VS2015 VB.Net

    Dim i As Integer

    For i = 0 To ListBox.ItemsCount - 1

      If the item is selected Then

        Do something

      Else

      Do something else

      End if

    Next

    I believe if the ListBox.SelectedItems count is greater than 0 then you can just iterate through that collection of selected items. I didn't test the code below though. Also it is recommended not to name an object with the same name used by an objects class I believe. So if you really named the ListBox "ListBox" then I would recommend altering the name to ListBox1 or something other than ListBox.

    If ListBox1.SelectedItems.Count > 0 Then

    ' Do something

    End If


    La vida loca

    Thursday, May 26, 2016 4:16 PM
  • DW,

    Maybe this will make it easier or, if not, at least more clear as to what's going on. I put a small class together that you can use so that you can know what's selected (and the text value of it along with the index of it) and what's not.

    The first point that I'd like to make is this: While it's typical that you'll use a ListBox with strings for the .Items collection, that's not what the control uses; it uses .Net objects (which can be anything, including a string). You'll see that when I cast to a string when I show the code, but first let me show you what I have here.

    A simple form with a ListBox (ListBox1) and a button (Button1):

    I populated the ListBox in code and since I know there are items in the .Items collection, I know it's ok to enable the button - but depending on how you're populating the ListBox, that might not be a safe assumption.

    As you can see, nothing is selected, but I'll click the button and see what it does (this will make more sense when you see the code):

    In the code, I have "Stop" which will work just like a breakpoint does; program execution will halt at that point and you can then hover your mouse over any variable which is then in scope and inspect its value.

    Hovering my mouse over the variable "data" above shows me this:

    There are two collections in the class which is returned to you: A collection of items which ARE selected and a collection of items which are NOT selected.

    Because they're collections, you need to expand each of them to see what they contain:

    As is not surprise here, the collection of selected items shows a length of zero so I'll look at the unselected collection:

    That shows there are three (again, no surprise). If I drill down one more level [each], you'll see the actual data:

    The other two are similar, obviously.

    Now I'll stop the program and restart it, this time selecting two of the items:

    When I click the button, the following shows what's returned from the class:

    The code for it is simpler than you might think:

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load With ListBox1 .SelectionMode = SelectionMode.MultiExtended .Items.AddRange(New String() _ {"Apples", _ "Oranges", _ "Pears"}) End With End Sub Private Sub _ Button1_Click(sender As System.Object, _ e As System.EventArgs) _ Handles Button1.Click Dim data As New TextListBoxData(ListBox1) Stop End Sub End Class Public Class TextListBoxData Private _selectedItems As IEnumerable(Of TextListBoxItems) Private _unselectedItems As IEnumerable(Of TextListBoxItems) Public Sub New(ByVal lb As ListBox) Try If lb Is Nothing Then Throw New ArgumentNullException("ListBox Control", "Cannot be null." & vbCrLf) Else If lb.Items.Count > 0 Then Dim selected As New List(Of TextListBoxItems) Dim unselected As New List(Of TextListBoxItems) For i As Integer = 0 To lb.Items.Count - 1 Dim item As Object = lb.Items(i) If lb.SelectedItems.Contains(item) Then selected.Add(New TextListBoxItems(i, DirectCast(item, String))) Else unselected.Add(New TextListBoxItems(i, DirectCast(item, String))) End If Next _selectedItems = selected.ToArray _unselectedItems = unselected.ToArray End If End If Catch ex As Exception Throw End Try End Sub Public ReadOnly Property SelectedItems As IEnumerable(Of TextListBoxItems) Get Return _selectedItems End Get End Property Public ReadOnly Property UnselectedItems As IEnumerable(Of TextListBoxItems) Get Return _unselectedItems End Get End Property Public Class TextListBoxItems Private _index As Integer Private _text As String Friend Sub New(ByVal index As Integer, _ ByVal text As String) If Not String.IsNullOrWhiteSpace(text) AndAlso index >= 0 Then _index = index _text = text.Trim End If End Sub Public ReadOnly Property Index As Integer Get Return _index End Get End Property Public ReadOnly Property Text As String Get Return _text End Get End Property End Class End Class


    Whether you actually use this or not is up to you, but hopefully you'll try it at least once and step through the code - you'll gain insight as to what's what and then you won't need it again.

    :)


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Thursday, May 26, 2016 6:34 PM