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
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
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.
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
I'm trying to refill my DataGridView after a filter selection in a combobox.
Here is my code where I try...at this moment the code is clearing the DataGridview and just fill only on row with only 1 cell..KlantID = 7
Any idea?
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
klantid = ComboBox1.SelectedValue
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim SQLstr As String
SQLstr = "SELECT * FROM tblKlant WHERE KlantID = #klantid"
Dim cmd As New OleDbCommand(SQLstr, myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(ds, "tblKlant")
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblKlant"
DataGridView1.Refresh()
End Sub
Why are you populating records on every combobox_SelectionChange event execution. Try to filter your data only instead of query execution.
And, better to use SelectedValueChanged event instead of SelectionChange.
Private Sub form_Load(sender As Object, e As EventArgs) Handles Me.Load
//Fill your data here with DataView
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim cmd As New OleDbCommand("SELECT * FROM tblKlant", myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim dt As New DataTable() 'Dont use dataset if your are not relating more than one tables
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(dt)
dt.TableName = "tblKlant"
cmd.ExecuteNonQuery()
DataGridView1.DataSource = dt.DefaultView
DataGridView1.DataMember = "tblKlant"
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
End Sub
Private Sub combobox_SelectedValueChanged(sender As Object, e As EventArgs) Handles combobox.SelectedValueChanged
IF combobox.SelectedValue IsNot Nothing Then
Dim dv As DataView = DirectCast(DataGridView1.DataSource, DataView)
dv.RowFilter = "KlantID=" + combobox.SelectedValue.ToString()
Else
dv.RowFilter = vbNullString
End IF
End Sub
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