JT4U
JT4U

Reputation: 620

How to handle multiple checked items and display them on a loop one by one in a msgbox

I want to get all the checked items from a CheckedListBox and add each item to a variable such as item1, item2, etc.

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim item1 As String
    Dim item2 As String
    For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
        If i = 1 Then
            item1 = CheckedListBox1.CheckedItems(i)
            MsgBox(item1)
        ElseIf i > 1 Then
            item1 = CheckedListBox1.CheckedItems(i)
            item2 = CheckedListBox1.CheckedItems(i)
            MsgBox(item1 + item2)
        End If
    Next
End Sub

How can I show all the selected items in a MsgBox?

Upvotes: 0

Views: 74

Answers (1)

Chris Dunaway
Chris Dunaway

Reputation: 11216

If the issue is just that you're not sure how to handle multiple checked items, just use a StringBuilder and not individual variables.

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim sb As New StringBuilder()

    For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
        sb.AppendLine(CheckedListBox1.CheckedItems(i))
    Next

    MsgBox(sb.ToString())

End Sub

As a side note, don't use + for concatenating strings, use the & operator.

Upvotes: 4

Related Questions