Start by fixing the
SQL Injection[
^] vulnerability in your code.
You should also wrap the
SqlCommand
and
SqlDataReader
objects in
Using
blocks, to ensure that their resources are always cleaned up.
You need to load a single field from your table - don't use
SELECT *
.
You need to store the values from that field in a collection - a
HashSet(Of T)
would be appropriate, as PIEBALDconsult suggested.
You then loop through each item in the list, using the stored values to determine whether or not it should be checked.
Something like this should work:
Dim checkedItems As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
Dim QueryBrands As String = "SELECT YourColumn FROM tblBrandsTerminals WHERE XIDTerminal = @TermXID"
Using commandsql As New SqlCommand(QueryBrands, con)
commandsql.Parameters.AddWithValue("@TermXID", TermXID.Text)
Using reader As SqlDataReader = commandsql.ExecuteReader()
While reader.Read()
checkedItems.Add(reader.GetString(0))
End While
End Using
End Using
For index As Integer = 0 To BrandListBox.Items.Count - 1
Dim drv As DataRowView = CType(BrandListBox.Items(index), DataRowView)
Dim value As String = Convert.ToString(drv(BrandListBox.ValueMember))
Dim isChecked As Boolean = checkedItems.Contains(value)
BrandListBox.SetItemChecked(index, isChecked)
Next