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

问题描述

我有一个带有一些值的复选框,比方说 “苹果” “桃” “柠檬” 这些值来自数据集。

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

编辑:就我而言,使用 sql 查询提供的数据集填充了清单框

解决方法

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

enter image description here

保存数据的容器

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

读取数据的类

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
,

您没有确切地提到 CheckedListBox 如何由 DataSet 填充,我假设您将字符串直接添加到 Items 集合。

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

    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
,

像这样使用 service-a: service-b: depends_on: service-a 方法:

SetItemChecked

注意,如果item不存在,会抛出异常,所以在调用CheckedListBox1.SetItemChecked(CheckedListBox1.Items.IndexOf("your item goes here"),True) 方法之前一定要检查item。为此,您可以检查 SetItemChecked() 的返回值。如果该项目不存在,则为 -1。