vb.netchecklistbox

How to check elements from an array in a CheckListBox


i have a checklisbox with some value, let's say "Apple" "Peach" "Lemon" These values came from a dataset.

I have an array with Apple and Lemon: {"Apple", "Lemon"}. How to check in the checklistbox each value read in this array?

EDIT: In my case, the checklistbox was populate using a dataset provided by a SQL query


Solution

  • In the following code sample, data from SQL-Server (database doesn't matter but this is what I used, what is important is the container the data is loaded into is loaded into a list.

    enter image description here

    Container to hold data

    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 to read data

    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
    

    Extension method

    Which can check or uncheck a value if found in the CheckedListBox and is case insensitive.

    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
    

    Form code

    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
    

    To check all at once

    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