JTUP JTUP - 6 months ago 29
Vb.net Question

Trying to add checked items from a checked list box which contains 7 or more items to variables to show in a msgbox

I am not able to get the output i want because i know there is something wrong i am doing with my code but not exactly what. Basically i want to get all the items i checked from the checkedlistbox and add each item to a variable such as item1, and item2. I know this is really basic but i tried my best to use my head being a new vb programmer.

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


basically what i want to show is lets say if more than 1 item was selected. i want that item to have an assigned variable value and display both items in a msgbox.

Answer

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.