gaurav somani
gaurav somani

Reputation: 215

how to store checked items in an array in CheckedListBox in vb.net

i'm storing all checked items in a string this works perfectly for me but i want to store all the checked items in an array with their names.

 Dim i As Integer

 Dim ListItems As String

        ListItems = "Checked Items:" & ControlChars.CrLf

        For i = 0 To (ChkListForPrint.Items.Count - 1)
            If ChkListForPrint.GetItemChecked(i) = True Then
                ListItems = ListItems & "Item " & (i + 1).ToString & " = " & ChkListForPrint.Items(i)("Name").ToString & ControlChars.CrLf
            End If
        Next

Please help!

Upvotes: 1

Views: 9897

Answers (2)

NeverHopeless
NeverHopeless

Reputation: 11233

If you need CheckedItems then why you are using Items instead ? I would recommend to use CheckedItems.

I have modified your code a bit and something like this would help you:

Dim collection As New List(Of String)()        ' collection to store check items
Dim ListItems As String = "Checked Items: "    ' A prefix for any item

For i As Integer = 0 To (ChkListForPrint.CheckedItems.Count - 1)  ' iterate on checked items
    collection.Add(ListItems & "Item " & (ChkListForPrint.Items.IndexOf(ChkListForPrint.CheckedItems(i)) + 1).ToString & " = " & ChkListForPrint.GetItemText(ChkListForPrint.CheckedItems(i)).ToString)  ' Add to collection
Next

Here:

  1. ChkListForPrint.Items.IndexOf(ChkListForPrint.CheckedItems(i)) will get the index of the item checked.

  2. ChkListForPrint.GetItemText(ChkListForPrint.CheckedItems(i)) will display the text of the item.

So would generate output like: (Assume 4 items in list in which 2 and 3 item is checked)

Checked Items: Item 2 = Apple
Checked Items: Item 3 = Banana

Upvotes: 1

WozzeC
WozzeC

Reputation: 2660

This should do it.

Dim ListItems as New List(Of String)
For i = 0 To (ChkListForPrint.Items.Count - 1)
    If ChkListForPrint.GetItemChecked(i) = True Then
       ListItems.Add(ChkListForPrint.Items(i)("Name").ToString)
    End If
Next

Upvotes: 1

Related Questions