1

我有一个将数据从 SQL Server 检索到 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()

结果很好,假设我有结果:

[ ]AA
[ ]BB
[ ]CC

我想检查是否有“BB”,然后它会自动检查“BB”,这样

[ ]AA
[X]BB
[ ]CC

我试过但失败了。喜欢的东西

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

为了尝试它是否确实返回了字符串,我测试了代码

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

它确实返回“AA”、“BB”、“CC”

4

1 回答 1

2

试试下面的代码

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()
于 2013-07-11T16:30:44.880 回答