簡體   English   中英

如何檢查 CheckListBox 中數組中的元素

[英]How to check elements from an array in a CheckListBox

我有一個帶有一些值的復選框,比如說“Apple”“Peach”“Lemon”這些值來自數據集。

我有一個蘋果和檸檬的數組:{“蘋果”,“檸檬”}。 如何在復選框中檢查該數組中讀取的每個值?

編輯:就我而言,復選框是使用 SQL 查詢提供的數據集填充的

在下面的代碼示例中,來自 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

您沒有確切提到CheckedListBox是如何被DataSet填充的,我假設您將 Strings 直接添加到 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

像這樣使用SetItemChecked方法:

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

請注意,如果該項目不存在,則會引發異常,因此請務必在調用SetItemChecked()方法之前檢查該項目。 為此,您可以檢查IndexOf()的返回值。 如果項目不存在,它將是 -1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM