【问题标题】:How to check elements from an array in a CheckListBox如何检查 CheckListBox 中数组中的元素
【发布时间】:2021-04-02 13:07:47
【问题描述】:

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

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

编辑:在我的例子中,复选框是使用 SQL 查询提供的数据集填充的

【问题讨论】:

    标签: vb.net checklistbox


    【解决方案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
    

    读取数据的类

    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
    

    【讨论】:

    • 谢谢凯伦这个非常详细的答案,它有效!顺便说一句,我不明白为什么处理清单框真的很复杂
    【解决方案2】:

    您没有具体提到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
    

    【讨论】:

      【解决方案3】:

      像这样使用SetItemChecked 方法:

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

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

      【讨论】:

        猜你喜欢
        • 2021-03-13
        • 2015-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-14
        • 1970-01-01
        相关资源
        最近更新 更多