Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
cmd.Connection = cm
cm.Open()
cmd.Connection = cm
cmd.CommandText = "SELECT * FROM studdetail WHERE name= '" & ComboBox2.Text & "' ORDER by name"
dr = cmd.ExecuteReader()
If dr.HasRows Then
While (dr.Read())
ComboBox2.Text = dr!name
TextBox1.Text = dr!Regno
TextBox2.Text = dr!class
TextBox3.Text = dr!division
ComboBox2.Items.Add(dr!name)
'DateTimePicker1.Value = dr!d1
'TextBox4.Text = dr!kannada
End While
End If
dr.Close()
cm.Close()
End Sub
Please Help How to debug this Error:The connetion was not closed.The connetion current state is open
Posted

1 solution

That's difficult - if not impossible - to debug without access to your machine and network, we can't replicate the problem here because we don't have enough information.
But a couple of things do spring to mind.
1) Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
2) Put a Try...Catch block around that whole code and report what the problem (if any) is. Chances are there is a problem elsewhere which is causing this.
3) Use Using blocks to automatically Close and Dispose your objects.
4) That's an odd command you have there: The ORDER BY is redundant because it only returns rows with the same name anyway...
VB
Try
    Using con As New SqlConnection(strConnect)
    	con.Open()
        Using com As New SqlCommand("SELECT * FROM studdetail WHERE [name]=@NM", con)
            com.Parameters.AddWithValue("@NM", ComboBox2.Text);
            Using dr As SqlDataReader = com.ExecuteReader()
                While dr.Read()
                    ComboBox2.Text = dr!name
                    TextBox1.Text = dr!Regno
                    TextBox2.Text = dr!class
                    TextBox3.Text = dr!division
                    ComboBox2.Items.Add(dr!name)
                End While
            End Using
        End Using
    End Using
Catch ex As Exception
    ' Report a problem using ex.Message
End Try

(And that While should probably be an If)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900