如何检查 CheckListBox 中数组中的元素

How to check elements from an array in a CheckListBox

我有一个具有一定价值的核对清单,比方说 “苹果” “桃” “柠檬” 这些值来自数据集。

我有一个包含 Apple 和 Lemon 的数组:{"Apple", "Lemon"}。 如何在检查列表框中检查此数组中读取的每个值?

编辑:就我而言,检查列表框是使用 SQL 查询

提供的数据集填充的

您没有具体说明 CheckedListBox 是如何被 DataSet 填充的,我假设您将字符串直接添加到 Items 集合中。

此代码将简单地遍历 CheckedListBox 并将值与数组进行比较,无论匹配结果如何,复选框都会被勾选或清除。

    Dim theArray() As String = {"Apple", "Lemon"}

    For counter As Integer = 0 To CheckedListBox1.Items.Count - 1

        Dim currentItem As String = CheckedListBox1.Items(counter).ToString

        Dim match As Boolean = theArray.Contains(currentItem.ToString)

        CheckedListBox1.SetItemChecked(counter, match)
    Next

像这样使用SetItemChecked方法:

CheckedListBox1.SetItemChecked(CheckedListBox1.Items.IndexOf("your item goes here"), True)

注意如果item不存在会抛出异常,所以在调用SetItemChecked()方法前一定要检查是否有item。为此,您可以检查 IndexOf() 的 return 值。如果该项不存在,则为-1。

在下面的代码示例中,数据来自SQL-Server(数据库并不重要,但这是我使用的,重要的是数据加载到的容器被加载到列表中。

保存数据的容器

Public Class Category
    Public Property Id() As Integer
    Public Property Name() As String

    Public Overrides Function ToString() As String
        Return Name
    End Function
End Class

Class读取数据

Imports System.Data.SqlClient

Public Class SqlOperations
    Private Shared ConnectionString As String =
                "Data Source=.\SQLEXPRESS;Initial Catalog=NorthWind2020;Integrated Security=True"

    Public Shared Function Categories() As List(Of Category)
        Dim categoriesList = New List(Of Category)
        Dim selectStatement = "SELECT CategoryID, CategoryName FROM Categories;"

        Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
            Using cmd As New SqlCommand With {.Connection = cn}

                cmd.CommandText = selectStatement

                cn.Open()

                Dim reader = cmd.ExecuteReader()
                While reader.Read()
                    categoriesList.Add(New Category() With {.Id = reader.GetInt32(0), .Name = reader.GetString(1)})
                End While


            End Using

        End Using

        Return categoriesList

    End Function

End Class

扩展方法

可以选中或取消选中在 CheckedListBox 中找到的值并且不区分大小写。

Public Module Extensions
    <Runtime.CompilerServices.Extension>
    Public Function SetCategory(sender As CheckedListBox, text As String, Optional checkedValue As Boolean = True) As Boolean

        If String.IsNullOrWhiteSpace(text) Then
            Return False
        End If

        Dim result = CType(sender.DataSource, List(Of Category)).
                Select(Function(item, index) New With
                          {
                            Key .Column = item,
                            Key .Index = index
                          }).FirstOrDefault(Function(this) _
                             String.Equals(this.Column.Name, text, StringComparison.OrdinalIgnoreCase))

        If result IsNot Nothing Then
            sender.SetItemChecked(result.Index, checkedValue)
            Return True
        Else
            Return False
        End If
    End Function

End Module

表单代码

Public Class ExampleForm
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckedListBox1.DataSource = SqlOperations.Categories
    End Sub

    Private Sub CheckCategoryButton_Click(sender As Object, e As EventArgs) Handles CheckCategoryButton.Click
        CheckedListBox1.SetCategory(CategoryToCheckTextBox.Text, StateCheckBox.Checked)
    End Sub
End Class

一次检查所有

Private Sub CheckAllButton_Click(sender As Object, e As EventArgs) Handles CheckAllButton.Click
    CType(CheckedListBox1.DataSource, List(Of Category)).
        ForEach(Sub(cat) CheckedListBox1.SetCategory(cat.Name, True))
End Sub