user2103670
user2103670

Reputation: 1721

Set Default Checked Items in a CheckedLIstBox VB.Net

I have a code that retrieve the data from SQL Server to a CheckedListBox

    Dim queryString As String = "SELECT Facility FROM Database.dbo.Facility"
    Dim connection As New SqlConnection(connectionString)
    Dim command As New SqlCommand(queryString, connection)
    connection.Open()
    Dim dataReader As SqlDataReader = command.ExecuteReader()
    Dim var As New DataTable
    Dim source As New BindingSource
    source.DataSource = dataReader
    CheckList_Facility.DataSource = source
    CheckList_Facility.ValueMember = "Facility"
    connection.Close()

The result works well, assume I have the result:

[ ]AA
[ ]BB
[ ]CC

I would like to check IF there is "BB" then it automatically checked "BB" so that

[ ]AA
[X]BB
[ ]CC

I tried but failed. Something likes

     For Each item In CheckedList_Facility.Items
        If (item("Facility").ToString() = "BBB") Then
            CheckedList_Region.SelectedValue = True
    Next

To try if it does actually return the string, I tested the code

For Each item In CheckedList_Facility.Items
    MsgBox(item("Facility").ToString())
Next

It does return "AA", "BB" , "CC"

Upvotes: 1

Views: 4408

Answers (1)

David -
David -

Reputation: 2031

Try the following code

Dim queryString As String = "SELECT Facility FROM Database.dbo.Facility"
Dim checkedValue As String = "BB"
Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)

connection.Open()

Dim dataReader As SqlDataReader = command.ExecuteReader()

If dataReader.HasRows Then
    Do While dataReader.Read
        Dim facility As String = dataReader.Item("Facility").ToString()
        Dim checkedState As Boolean = facility = checkedValue

        CheckList_Facility.Items.Add(facility, checkedState)
    Loop
End If

connection.Close()

Upvotes: 2

Related Questions