"when I run the code there is no error" there's no error because you have an empty catch. Why are empty catch blocks a bad idea?
The error is that the command has no connection assigned. This should work:
cmd = New SqlCommand("INSERT INTO players (name) VALUES (" & ListBox3.Items(J).ToString & ")")
cmd.Connection = Conn
You should also get familiar with the Using
-statement and use that on all objects that implement IDisposable
like SqlConnection
which ensures that it gets dispoed/closed always(even on error).
Last but not least: always use SQL-Parameters instead of string concatenation to prevent sql-injection:
Using conn As New SqlConnection("SERVER=MAXPAYNE-PC\DEVELOPER;DATABASE=sample;User=sa;Pwd=bwd")
Dim sql = "INSERT INTO players (name) VALUES (@name)"
Using cmd As New SqlCommand(sql, conn)
Dim nameParameter = New SqlParameter("@name", SqlDbType.NVarChar)
cmd.Parameters.Add(nameParameter)
conn.Open()
For Each name As String In ListBox3.Items
cmd.Parameters("@name").Value = name
Try
Dim inserted As Int32 = cmd.ExecuteNonQuery()
Catch ex As Exception
' do something meaningful here (f.e. logging or at least output the error) '
' empty catches are evil in most cases since they conceal problems from you but not from the users '
Throw
End Try
Next
End Using
End Using ' conn.Close not needed due to the Using '