我有一个代码,用于将数据从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”
答案 0 :(得分: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()