Hello Friends please i am in trouble with ExecuteNonQuery() and my connection and i need your help. I have been trying to build a small program and seem to have been lost as to how to solve my problem.
The exception details are
Exception Details:InvalidOperationException was Unhandled
ExecuteNonQuery: Connection property has not been initialized
The Source of error is
cmd.ExecuteNonQuery()
and my relevant code is shown below
For Connection:
Private Sub FrmStudent_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
OleDbConnection1.ConnectionString = strCon
Refresh_Form()
End Sub
Module ModuleConnection
Public Con As System.Data.OleDb.OleDbConnection
Public U, P, S, D, strCon As String
Public ObjCon As FrmConnection
Public Sub prcConnect(ByVal U, ByVal P, ByVal S, ByVal D)
Try
strCon = "provider=SQLOLEDB;User id=" & U & ";Password=" & P & ";Server=" & S & ";database=" & D
Con = New System.Data.OleDb.OleDbConnection(strCon)
Con.Open()
MsgBox("Connection to the Database is Successful", MsgBoxStyle.Information, "Welcome")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error Connecting To Database")
ObjCon = New FrmConnection
ObjCon.Show()
End Try
End Sub
End Module
For ExecuteNonQuery():
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
If Len(Trim(txtstudCd.Text)) = 0 Then
MessageBox.Show("Please Student Id cannot be blank", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
If Len(Trim(txtFirstName.Text)) = 0 Then
MsgBox("Please FirstName cannot be blank", MsgBoxStyle.OkOnly, "Enter Name")
Exit Sub
End If
If Len(Trim(txtLastName.Text)) = 0 Then
MsgBox("Please LastName cannot be blank", MsgBoxStyle.OkOnly, "Enter Name")
Exit Sub
End If
If Not IsNumeric(txtAge.Text) Then
MessageBox.Show("Please Age must be Numeric value", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtAge.Text = ""
txtAge.Focus()
Exit Sub
End If
If Not IsNumeric(txtstudCd.Text) Then
MessageBox.Show("Please Student Id must be Numeric Value", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtstudCd.Text = ""
txtstudCd.Focus()
End If
Dim Con As New OleDb.OleDbConnection(strCon)
Dim strSQL As String = _
"INSERT INTO Student (StudentCode, FirstName, LastName, Age)" & _
" VALUES(@StudentCode, @FirstName, @LastName, @Age )"
Dim cmd As New OleDb.OleDbCommand(strCon)
With cmd
.Parameters.Add(New OleDb.OleDbParameter("@StudentCode", SqlDbType.NVarChar, 6)).Value = txtstudCd.Text
.Parameters.Add(New OleDb.OleDbParameter("@FirstName", SqlDbType.NVarChar, 30)).Value = txtFirstName.Text
.Parameters.Add(New OleDb.OleDbParameter("@LastName", SqlDbType.NVarChar, 30)).Value = txtLastName.Text
.Parameters.Add(New OleDb.OleDbParameter("@Age", SqlDbType.NVarChar, 3)).Value = txtAge.Text
End With
Con.Open()
cmd.ExecuteNonQuery()
Con.Close()
MsgBox("Data Saved", MsgBoxStyle.Information, "Hello")
Refresh_Form()
End Sub