2012-11-15 68 views
1

我將所有選中的項存儲在一個字符串中,這對我來說非常合適,但我想將所有選中的項存儲在數組中並將其與名稱一起存儲。如何將選中的項存儲在vb.net的CheckedListBox中的數組中

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 

請幫忙!

回答

0

這應該這樣做。

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 
+0

感謝您的答覆...工作對我來說.. :) –

1

如果您需要CheckedItems那麼爲什麼您使用Items而不是?我會建議使用CheckedItems

我已經修改了你的代碼了一下,像這樣的東西會幫助你:

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 

這裏:

  1. ChkListForPrint.Items.IndexOf(ChkListForPrint.CheckedItems(i)) 將得到檢查項目的索引。

  2. ChkListForPrint.GetItemText(ChkListForPrint.CheckedItems(i))將 顯示該項目的文本。

像這樣將產生輸出:(假設在列表4項,其中2和3項檢查)

Checked Items: Item 2 = Apple 
Checked Items: Item 3 = Banana 
相關問題