Connection property has not been initialized - VB.net ExecuteNonQuery Error [duplicate] - vb.net

Getting an error here not sure why its not opening the connection. Hoping someone can help me.
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
Dim con As SqlConnection
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
Dim cmdInsert As New SqlCommand(Sqlstr, con)
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
Using connection As New SqlConnection(connectionString)
connection.Open()
cmdInsert.Parameters.Add("#FirstName", Data.SqlDbType.NVarChar).Value = FirstName.Text()
cmdInsert.Parameters.Add("#LastName", Data.SqlDbType.NVarChar).Value = LastName.Text
cmdInsert.Parameters.Add("#Email", Data.SqlDbType.NVarChar).Value = Email.Text
cmdInsert.Parameters.Add("#Phone", Data.SqlDbType.NChar).Value = Phone.Text
cmdInsert.Parameters.Add("#Address", Data.SqlDbType.NVarChar).Value = Address.Text
cmdInsert.Parameters.Add("#City", Data.SqlDbType.NVarChar).Value = City.Text
cmdInsert.Parameters.Add("#State", Data.SqlDbType.NVarChar).Value = State.Text
cmdInsert.Parameters.Add("#Zip", Data.SqlDbType.NChar).Value = Zip.Text
cmdInsert.ExecuteNonQuery()
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try

You have two SqlConnection objects - one in Dim con As SqlConnection and then another in your using statement. Create the SqlCommand after the using statement and pass the connection in to the constructor.

You have the wrong scope -- you're instantiating your SqlCommand before instantiating and opening the actual SQL connection you're trying to use to execute the command.
I believe this is what will fix your code (I moved the insert call into the using scope):
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmdInsert As New SqlCommand(Sqlstr, connection) <----- **** Moved this here, changed the connection
cmdInsert.Parameters.Add("#FirstName", Data.SqlDbType.NVarChar).Value = FirstName.Text()
cmdInsert.Parameters.Add("#LastName", Data.SqlDbType.NVarChar).Value = LastName.Text
cmdInsert.Parameters.Add("#Email", Data.SqlDbType.NVarChar).Value = Email.Text
cmdInsert.Parameters.Add("#Phone", Data.SqlDbType.NChar).Value = Phone.Text
cmdInsert.Parameters.Add("#Address", Data.SqlDbType.NVarChar).Value = Address.Text
cmdInsert.Parameters.Add("#City", Data.SqlDbType.NVarChar).Value = City.Text
cmdInsert.Parameters.Add("#State", Data.SqlDbType.NVarChar).Value = State.Text
cmdInsert.Parameters.Add("#Zip", Data.SqlDbType.NChar).Value = Zip.Text
cmdInsert.ExecuteNonQuery()
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try

Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
' =================================================
' This is a declaration, not an instantiation
' =================================================
Dim con As SqlConnection
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
' =================================================
' con is Nothing here
' =================================================
Dim cmdInsert As New SqlCommand(Sqlstr, con)
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
' =================================================
' connection is not what you passed to cmdInsert
' =================================================
Using connection As New SqlConnection(connectionString)
connection.Open()

Connection Sting Property Error always occur when the connection is not declared/renewed
the solution is simple
dim con as new SqlConnection
con.connectionString = "Provide your SQL connection"
con.open
'write code or action you want to perform
con.close
Hope it helps.

Related

Setting a variable to the highest value in Access Database ASP.NET

I want to set a variable to a value in an Access Database table from aspx.vb. I want to return the highest "PalletNumber" to txbPalletNumber textbox. What am I doing wrong?
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim cmd As New OleDbCommand
Try
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT PalletNumber, MAX(PalletNumber) FROM
tblPalletNumber"
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
Catch ex As Exception
'Error handling
End Try
txbPackday.Text = DateAndTime.Now
End Sub
Here is the solution. Thanks for all the help.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim test As String
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
Dim cmd As New OleDbCommand
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT MAX(PalletNumber) FROM tblPalletNumber"
test = cmd.ExecuteScalar()
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
txbPackday.Text = DateAndTime.Now
End Sub

Register Form Issues VB.Net

I am having an issue when I am setting up this Register form.
My current code is this:
Public Class Form2
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, con)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, con)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
I am having the issue at connection.open(). The error that I am having is
The ConnectionString property has not been initialized.
I have been trying for the past hour to find different ways to write to the database but to no prevail and I cannot figure this out.
[In response to Steve
My code after editing and still the same error
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, connection)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
connection.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
Global variables could be very ....evil. Expecially if you name them with the same name of a local variable.
Me.connection is not the same variable connection declared as local variable inside the sub. You set the connection string on the global variable then use the local variable without any connection string
Change these two lines
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
removing the Me.
connection.ConnectionString = dbProvider & dbSource
connection.Open()
and don't open the connection two times.
In any case, you don't need the adapter at all to execute an insert command
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
sql = "INSERT INTO Robocopy(username,[password]) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = new OleDb.OleDbCommand(sql, connection )
connection.Open()
cmd.ExecuteNonQuery()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
End Sub
I see also that you have commented out the Parameterized approach to your query. Please do yourself a favour and restore as soon as possible the parameters logic. It is a lot more safe and avoids numerous errors
Finally Password is a reserved keyword in Access.Use square brakets around it otherwise you will see an unexplicable "Syntax Error" in your insert command

Delete From Table error

i'm trying to create a delete button to delete a record ....
here's my code:
Dim SqlQuery As String = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
'id is public shared as integer , which is ListView1.SelectedItems(0).Text
Dim SqlCommand As New OleDb.OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
I get an exception in .ExecuteNonQuery(), the error is
"ExecuteNonQuery() requires the command to have a transaction" ,
"Validate transaction" , "ExecuteReaderInternal"
assume that the database is connected, got info and delete button is button3 .
Also i will show you my whole form code:
Public Class Report
Public id As Integer
Public conn As New OleDb.OleDbConnection
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ramy\Documents\Beach.accdb"
Private Property RivieraDataSet As Object
Private Sub Report_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
conn.Close()
End Sub
Private Sub Report_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If conn.State = ConnectionState.Closed Then
Try
conn.ConnectionString = connstring
conn.Open()
MsgBox("DataBase opened successfully!", MsgBoxStyle.Exclamation)
loadlistview()
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.Critical)
End Try
Else
MsgBox("DataBase Error!!", MsgBoxStyle.Critical)
End If
Dim reading As OleDb.OleDbDataReader
Dim cmd As New OleDb.OleDbCommand
Dim trans As OleDb.OleDbTransaction
trans = conn.BeginTransaction
cmd.CommandText = "SELECT * FROM MyTable"
cmd.Connection = conn
cmd.Transaction = trans
reading = cmd.ExecuteReader
Dim i
Do While reading.Read
i = Val(reading.Item("Total")) + i
Loop
TextBox7.Text = i
TextBox7.Text = Convert.ToDecimal(TextBox7.Text).ToString("N2") & " L.E"
End Sub
Sub loadlistview()
ListView1.FullRowSelect = True
ListView1.MultiSelect = False
ListView1.View = View.Details
ListView1.Columns.Clear()
ListView1.Items.Clear()
ListView1.Columns.Add("No", 30, HorizontalAlignment.Left)
ListView1.Columns.Add("InvoiceDate", 125, HorizontalAlignment.Left)
ListView1.Columns.Add("PersonsNumber", 70, HorizontalAlignment.Left)
ListView1.Columns.Add("PersonPrice", 80, HorizontalAlignment.Left)
ListView1.Columns.Add("CashierName", 100, HorizontalAlignment.Left)
ListView1.Columns.Add("Total", 100, HorizontalAlignment.Left)
Dim SqlQuery As String = "SELECT * FROM MyTable"
Dim SqlCommand As New OleDb.OleDbCommand
Dim SqlAdapter As New OleDb.OleDbDataAdapter
Dim table As New DataTable
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
.Fill(table)
End With
For i = 0 To table.Rows.Count - 1
With ListView1
.Items.Add(table.Rows(i)("InvoiceNumber"))
With .Items(.Items.Count - 1).SubItems
.Add(table.Rows(i)("InvoiceDate"))
.Add(table.Rows(i)("PersonsNumber"))
.Add(table.Rows(i)("PersonPrice"))
.Add(table.Rows(i)("CashierName"))
.Add(table.Rows(i)("Total"))
End With
End With
Next
End Sub
Private Sub ListView1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView1.MouseClick
Dim SqlQuery As String = "SELECT * FROM MyTable"
Dim SqlCommand As New OleDb.OleDbCommand
Dim SqlAdapter As New OleDb.OleDbDataAdapter
Dim table As New DataTable
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
End With
If ListView1.SelectedItems.Count > 0 Then
id = ListView1.SelectedItems(0).Text
TextBox1.Text = id
TextBox6.Text = ListView1.SelectedItems(0).SubItems(1).Text
TextBox3.Text = ListView1.SelectedItems(0).SubItems(2).Text
TextBox4.Text = ListView1.SelectedItems(0).SubItems(3).Text
TextBox2.Text = ListView1.SelectedItems(0).SubItems(4).Text
TextBox5.Text = ListView1.SelectedItems(0).SubItems(5).Text
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim SqlQuery As String = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
'id is public shared as integer , which is ListView1.SelectedItems(0).Text
Dim SqlCommand As New OleDb.OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
End Sub
End Class
I was searching for a mistake in my delete btn code for hours , but i can see everything is good..... but .ExecuteNonQuery() is so annoying .
In your Form_Load you open a transaction for your GLOBAL connection.
This means that every command executed using that connection should be informed of this transaction (and you do it in the Form_Load event setting the Command.Transaction property).
But in other parts of your program, executing a command with that connection and not setting the Transaction property will raise the mentioned error.
Looking at your code above I would suggest to remove altogether the Transaction because, as is, you don't need it.
Simply remove these lines in Form_Load
Dim trans As OleDb.OleDbTransaction
trans = conn.BeginTransaction
...
cmd.Transaction = trans
Instead, if for motives not apparent from the code above, you insist in keeping the Transaction then you should create the command from the connection so the transaction is passed to the command.
Dim SqlQuery As String = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
Dim SqlCommand = conn.CreateCommand()
With SqlCommand
....
End With
By the way, I really suggest you to remove that global connection variable. It is only a source of problems (check if open, transactions etc...) Just make a function that creates it for you and use it in a Using Statement whenever you need it
Public Function GetConnection() As OleDb.OleDbConnection
Dim conn = New OleDb.OleDbConnection(connstring)
conn.Open()
return conn
End Function
And use it with Using Statement that close and dispose the enclosed object also in case of exceptions
Using conn = GetConnection()
Using command = conn.CreateCommand()
With command
command.CommandText = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
command.ExecuteNonQuery()
End With
End Using
End Using
Pay also attention at possible sql injection scenarios. In your situation (reading an integer from a ListView) there are few problems, but a parameterized query is always better

specified cast is not valid

Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.
Here is the code:
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath &
"\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
Conn.ConnectionString = connstring
Conn.Open()
LoadValue( )
End Sub
Private Sub LoadValue( )
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
TextBox1.Text = reader.GetString(0)
i = TextBox1.Text + 1
TextBox1.Text = i
reader.Close()
End If
End With
End Sub
The table reference:
Exception Error:
I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.
try this,
Private Sub LoadValue()
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
Dim tmpVal As Object = reader.Item(0)
TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())
i = CInt(TextBox1.Text) + 1
TextBox1.Text = i.ToString()
reader.Close()
End If
End With
End Sub

ExecuteNonQuery: Connection property has not been initialized VB

Getting an error here not sure why its not opening the connection. Hoping someone can help me.
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
Dim con As SqlConnection
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
Dim cmdInsert As New SqlCommand(Sqlstr, con)
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
Using connection As New SqlConnection(connectionString)
connection.Open()
cmdInsert.Parameters.Add("#FirstName", Data.SqlDbType.NVarChar).Value = FirstName.Text()
cmdInsert.Parameters.Add("#LastName", Data.SqlDbType.NVarChar).Value = LastName.Text
cmdInsert.Parameters.Add("#Email", Data.SqlDbType.NVarChar).Value = Email.Text
cmdInsert.Parameters.Add("#Phone", Data.SqlDbType.NChar).Value = Phone.Text
cmdInsert.Parameters.Add("#Address", Data.SqlDbType.NVarChar).Value = Address.Text
cmdInsert.Parameters.Add("#City", Data.SqlDbType.NVarChar).Value = City.Text
cmdInsert.Parameters.Add("#State", Data.SqlDbType.NVarChar).Value = State.Text
cmdInsert.Parameters.Add("#Zip", Data.SqlDbType.NChar).Value = Zip.Text
cmdInsert.ExecuteNonQuery()
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
You have two SqlConnection objects - one in Dim con As SqlConnection and then another in your using statement. Create the SqlCommand after the using statement and pass the connection in to the constructor.
You have the wrong scope -- you're instantiating your SqlCommand before instantiating and opening the actual SQL connection you're trying to use to execute the command.
I believe this is what will fix your code (I moved the insert call into the using scope):
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmdInsert As New SqlCommand(Sqlstr, connection) <----- **** Moved this here, changed the connection
cmdInsert.Parameters.Add("#FirstName", Data.SqlDbType.NVarChar).Value = FirstName.Text()
cmdInsert.Parameters.Add("#LastName", Data.SqlDbType.NVarChar).Value = LastName.Text
cmdInsert.Parameters.Add("#Email", Data.SqlDbType.NVarChar).Value = Email.Text
cmdInsert.Parameters.Add("#Phone", Data.SqlDbType.NChar).Value = Phone.Text
cmdInsert.Parameters.Add("#Address", Data.SqlDbType.NVarChar).Value = Address.Text
cmdInsert.Parameters.Add("#City", Data.SqlDbType.NVarChar).Value = City.Text
cmdInsert.Parameters.Add("#State", Data.SqlDbType.NVarChar).Value = State.Text
cmdInsert.Parameters.Add("#Zip", Data.SqlDbType.NChar).Value = Zip.Text
cmdInsert.ExecuteNonQuery()
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
Dim Sqlstr As String
' =================================================
' This is a declaration, not an instantiation
' =================================================
Dim con As SqlConnection
Dim connectionString As String = "Data Source=DB\TEST;Initial Catalog=Orders;Integrated Security=True"
' =================================================
' con is Nothing here
' =================================================
Dim cmdInsert As New SqlCommand(Sqlstr, con)
Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (#FirstName,#LastName,#Email,#Phone,#Address,#City,#State,#Zip)"
Try
' =================================================
' connection is not what you passed to cmdInsert
' =================================================
Using connection As New SqlConnection(connectionString)
connection.Open()
Connection Sting Property Error always occur when the connection is not declared/renewed
the solution is simple
dim con as new SqlConnection
con.connectionString = "Provide your SQL connection"
con.open
'write code or action you want to perform
con.close
Hope it helps.