troubleshooting Question

I need help with my VB code trying to fill a checkedlistbox and check items based on a value in SQL

Avatar of OHACI
OHACIFlag for United States of America asked on
Visual Basic.NETVB ScriptSQL
7 Comments1 Solution226 ViewsLast Modified:
I am trying to read in all columns in a SQL table to a VB checklistbox item and then check the ones that have a "checked" value of 1 in SQL.
Everything is working except it throws an exception when I get to the line where it is supposed to check one.
I am a pretty basic skilled programmer.
Any help is appreciated.
The line below that throws the exception is CheckedListBox1.SetItemCheckState(Index, CheckState.Checked)
Here is my code:
  Dim connectionString As String
        Dim cnn As SqlClient.SqlConnection
        Dim cmd As SqlClient.SqlCommand
        Dim sql As String
        Dim reader As SqlClient.SqlDataReader
        Dim i As Integer = 0
        Dim td As DateTime = DateTime.Now
        Dim Newdate = td.ToString("yyyy-MM-dd")

        connectionString = "Data Source=SQLSERVER\SQLEXPRESS;Initial Catalog=DBName;Persist Security Info=True;User ID=FakeID;Password=FakePassword"
        sql = "select CONVERT(VARCHAR(10), AddTime, 120),PatientMRN,PatientName,Checked,Completed from CarePlanOCR where CONVERT(VARCHAR(10), DateColumn, 120) = '" + Newdate + "'" + " order by CONVERT(VARCHAR(10), AddTime, 120)"
        cnn = New SqlClient.SqlConnection(connectionString)
        Try
            cnn.Open()
            cmd = New SqlClient.SqlCommand(sql, cnn)
            reader = cmd.ExecuteReader()
            reader.Read()
            While reader.Read()
                Dim checkedstate As Integer = reader.Item(3)
                'Add based on checked state
                If checkedstate = 1 Then

                    Dim Index As Integer = CheckedListBox1.Items.Add(reader.Item(0) + " - " + reader.Item(1) + " - " + reader.Item(2))
                    CheckedListBox1.SetItemCheckState(Index, CheckState.Checked)


                Else
                    Dim index As Integer = CheckedListBox1.Items.Add(reader.Item(0) + " - " + reader.Item(1) + " - " + reader.Item(2))

                End If

            End While
            reader.Close()
            cmd.Dispose()
            cnn.Close()

        Catch ex As Exception
            MsgBox("Can not open connection ! ")
        End Try
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros