【问题标题】:how to store checked items in an array in CheckedListBox in vb.net如何在vb.net的CheckedListBox中将选中的项目存储在数组中
【发布时间】:2012-11-15 08:11:01
【问题描述】:

我将所有选中的项目存储在一个字符串中,这对我来说非常有效,但我想将所有选中的项目及其名称存储在一个数组中。

 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

请帮忙!

【问题讨论】:

    标签: arrays vb.net checkedlistbox


    【解决方案1】:

    应该这样做。

    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
    

    【讨论】:

      【解决方案2】:

      如果您需要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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 2014-09-12
        • 2017-09-19
        相关资源
        最近更新 更多