I am trying to insert data to database, but getting error as ExecuteNonQuery: Connection property has not been initialized.
Everything seems ok with the connection.
Imports System.Data.SqlClient
Public Class crud1
Private Sub Add_btn_Click(sender As Object, e As EventArgs) Handles Add_btn.Click
Try
Dim conn_ As New SqlConnection("Data Source=DESKTOP-VVM5A31;Initial Catalog=temp;Integrated Security=True")
conn_.Open()
Dim command As New SqlCommand("INSERT INTO STUDENT (student_name, student_age) VALUES (@NAME, @AGE)")
command.Parameters.AddWithValue("@NAME", TXT_NAME.Text)
command.Parameters.AddWithValue("@AGE", Convert.ToInt32(TXT_AGE.Text))
command.ExecuteNonQuery()
MsgBox("Record saved.", MsgBoxStyle.Information)
conn_.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
Please see the image for the connection property.
CodePudding user response:
You are right taking into account that the command needs the connection open, before execute the command, and you are doing right.
But you are not telling to the command which is the connection to be used.
An easy way to do it would be something like this, before execute the command:
command.Connection = conn_