the connectionstring property has not been initialized in vb.net - vb.net

Everytime I click the button where the sub procedure execute, I'm getting the error "the connection string property has not been initialized"
Here is my code
Sub CheckExistingExp()
Dim aexpcheckifexisting As New DataSet
Dim bexpcheckifexisting As New OleDb.OleDbDataAdapter
Dim sqlcheck As String
Dim duplicateexp As Integer
sqlcheck = "select count(exp_doc) vcount from csap_exph where exp_doc = '" & RQuote(txtExpDoc.Text) & "' and status = 'A'"
bexpcheckifexisting = New OleDb.OleDbDataAdapter(sqlcheck, con)
bexpcheckifexisting.Fill(aexpcheckifexisting, "checkduplicateexp")
duplicateexp = aexpcheckifexisting.Tables("checkduplicateexp").Rows(0).Item("vcount")
If duplicateexp > 0 Then
If MsgBox("Expense Doc is already existing, are you sure you want to tag it as posted?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Approve_Expense()
Else
con.Close()
End If
End If
End Sub
What should I do to solve this?
Thanks.

Let alone the connection string which is missing, where did you open con for you to close it? [con.open()] and if your user hits MsgBoxResult.Yes your connection would stay open cause con.Close() is only called if duplicateexp <= 0.
dispose your con at the end of your code or use using which closes it automatically and use a try-catch to catch any errors.
have your connection string somewhere in app.config or make it public in a class or module or whatever you prefer and make your string = that value and open your connection at the beginning of the sub.

Related

"No value given for one or more required parameters" error using OleDbCommand

I am trying to update a record in MS Access using VB.net. This code will be under the "Delivered" button. When I try to run it, it shows the "No value given for one or more required parameters" error. Here is my code:
Private Const strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Traicy\Downloads\MWL(11-30-2021)\MadeWithLove\MadeWithLove\MadeWithLove.mdb;"
ReadOnly conn As OleDbConnection = New OleDbConnection(strConn)
Dim cmd As OleDbCommand
Public Sub DeliveredUpdate()
Const SQL As String = "UPDATE DELIVERY SET delivery_status = #status"
cmd = New OleDbCommand(SQL, conn)
' Update parameter
cmd.Parameters.AddWithValue("#status", "Delivered")
' Open connection, update, then close connection
Try
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("The delivery status was successfully updated.")
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
conn.Close()
End Try
End Sub
Do not declare connections or commands outside of the method where they are used. These database objects use unmanaged resources. They release these resources in their Dispose methods. The language provides Using blocks to handle this.
As mentioned in comments by Andrew Morton, you should have a Where clause to tell the database which record to update. This would contain the primary key of the record. I guessed at a name for the field, OrderID. Check your database for the real field name.
Access does not use named parameters but you can use names for readability. Access will be able to recognize the parameters as long as they are added to the Parameters collection in the same order that they appear in the sql string. In some databases the Add method is superior to AddWithValue because it doesn't leave the datatype to chance.
It is a good idea to separate your database code from your user interface code. If you want to show a message box in your Catch put the Try blocks in the UI code. This way your function can be used in a web app or mobile app without rewriting.
Public Function DeliveredUpdate(ID As Integer) As Integer
Dim recordsUpdated As Integer
Dim SQL As String = "UPDATE DELIVERY SET delivery_status = #status Where OrderID = #Id;"
Using conn As New OleDbConnection(strConn),
cmd As New OleDbCommand(SQL, conn)
cmd.Parameters.Add("#status", OleDbType.VarChar).Value = "Delivered"
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = ID
conn.Open()
recordsUpdated = cmd.ExecuteNonQuery
End Using 'closes and disposes the command and connection
Return recordsUpdated
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim retVal As Integer
Dim id As Integer = 1 'not sure where you are getting this value from
Try
retVal = DeliveredUpdate(id)
Catch ex As Exception
MsgBox(ex.Message)
End Try
If retVal > 0 Then
MsgBox("The delivery status was successfully updated.")
End If
End Sub

"Connection was not closed. Connection's current State was open"- Ms Access Visual Basic- Visual Studio 2010

My connection between my project and my Ms Access 2010 Database seems to be right at the moment of logging in with my project. However, After the first trial(if user and/or password are incorrect), when I try to log in again, the error is given. It says "Connection was not closed. Connection's current State was open". I just have found possible solutions for MySql service, but I'm using Ms Access database. The code where the error seems to be given is the following. Any suggestions?, please:
Public Function Validation()
da.Fill(dt)
connection.Open()
For Each DataRow In dt.Rows
If txtUser.Text = DataRow.Item(0) And txtPassword.Text = DataRow(1) Then
If cmbAccountType.Text = DataRow(2) Then
connection.Close()
Return True
End If
End If
Next
Return False
End Function
Why are you opening the connection in the first place? You're not using it between the Open and Close calls so what's the point? The Fill method will automatically open the connection if it's currently closed and then it will automatically close it again if it opened it, i.e. Fill and Update will open the connection if necessary and then leave it in its original state afterwards. Get rid of both the Open and Close calls.
To begin with, Function's in vb.net require a DataType. I have no idea what da.Fill(dt) is doing in this function. If you didn't have an open connection you wouldn't be able to fill anything but then on the next line you open some unknown connection from somewhere.
OleDb pays no attention to the names of parameters. The position of the parameters in the sql string must match the order that the parameters are added to the parameters collection.
Here is one approach.
Private ConnStr As String = "Your connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Validation(txtUser.Text, txtPassword.Text, cmbAccountType.Text) Then
'Do something
End If
End Sub
Public Function Validation(UName As String, PWord As String, Type As String) As Boolean
Dim Count As Integer
Using cn As New OleDbConnection(ConnStr),
cmd As New OleDbCommand("Select Count(*) From SomeTable Where User = #User And Password = #Password And AccountType = #Type;", cn)
cmd.Parameters.Add("#User", OleDbType.VarChar).Value = UName
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = PWord
cmd.Parameters.Add("#Type", OleDbType.VarChar).Value = Type
cn.Open()
Count = CInt(cmd.ExecuteScalar)
End Using
If Count > 0 Then
Return True
End If
Return False
End Function
Of course you should NEVER store passwords as plain text.

Having the ExecuteNonQuery : connection property has not been initialized

I'm trying to delete an entry from my database. But when the ExecuteNonQuery has to do it's job it can't find the enabled connection and give me this error :
System.InvalidOperationException :'ExecuteNonQuery : connection property has not been initialized'
Here is what I did :
Dim delete As New OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim dt As DataTable
initConnectionDtb(pathDtb)
openConnection()
If TextBox2.Text <> "" Then
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
MsgBox("USER HAS BEEN DELETED")
Else
MsgBox("ERROR")
End If
I could check if it was properly connected to the Database thanks to connectionName.State
I also enterily rewrote the connetion to the database in the function but ExecuteNonQuery still couldn't connect even though the connection was opened
I saw that i'm not the only one on this website but none of the previous answers have helped me.
#Filburt pointed out, how are you assigning your connection to your command object. Here is an example :
Using connection As OleDbConnection = New OleDbConnection(connectionString)
connection.Open()
Dim command As OleDbCommand = New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()
End Using
In your code, you need to assign the connection object to your command object. We can't see what code you have in initConnectionDtb(pathDtb) or openConnection()
To adapt this to your code:
delete.Connection = <<your connection object here>>
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
Another note: look into parameterizing your query strings instead of hand stringing the values. This will prevent issues with TextBox2.Text having a value like O'Toole which will cause a syntax error as well as SQL Injection.
Here's what i used to initialize my connection :
Public Function initConnectionDtb(ByVal path As String) As Boolean
initConnectionDtb = True
Connection = New OleDbConnection
Try
Connection.ConnectionString = "provider=microsoft.jet.oledb.4.0;" & "data source= " & path & ";"
Catch ex As Exception
Return False
End Try
End Function
Public Function openConnection() As Boolean
openConnection = True
Try
Connection.Open()
MsgBox(Connection.State) 'to test if my connection really openned in my previous post
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub closeConnection()
If Not IsNothing(Connection) Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
MsgBox(Connection.State)
Connection.Dispose()
Connection = Nothing
End If
End Sub
So far it worked for everything i tried (adding someone to the database for exemple)

i am trying to use an input from the user as part of a connection string to a SQL database

my connection string is saved in a string variable names str
what i am trying to do is use an input from the user as part of the string
the parts i want to take from the user are the ID and PASS
i am simply trying to check the connection statues with the ID and the PASS as inputs from the user.
Dim str As String = "Data Source=DESKTOP;uid=ID;pwd=PASS;database=DB"
Dim conn As New SqlConnection(str)
Private Sub btnconnect_Click(sender As Object, e As EventArgs) Handles btnconnect.Click
PW = txtadminpass.Text
Try
conn.Open()
conn.Close()
MsgBox("GOOD")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
i haven't had much like while using the + and & for the strings.
any help would be appreciated.
The SqlConnectionStringBuilder is an appropriate class to use in this case. You can add parts of the connection string to it via properties, so there is no chance of making mistakes:
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim csb As New SqlConnectionStringBuilder
csb.DataSource = "DESKTOP"
csb.InitialCatalog = "DB"
csb.UserID = "z"
csb.Password = "x"
' output "Data Source=DESKTOP;Initial Catalog=DB;User ID=z;Password=x" '
Console.WriteLine(csb.ToString())
Console.ReadLine()
End Sub
End Module
So, you need to check if the user is allowed to log into the database or not. The way you have followed looks good, you define the connection string based on the given ID and password, and you try to establish a connection, if it fails, the user can't log in, else he can do that.
However, the way you defined the string is wrong, you must use concatenation to preserve the ID and password values, try this,
Dim str As String = "Data Source=DESKTOP; uid=" & ID & "; pwd=" & PASS & ";database=DB"
Another way, which makes it easy to read:
Const CONN_STRING As String = "Data Source=DESKTOP;uid={0};pwd={1};database=DB"
Dim connString As String = String.Format(CONN_STRING, txtUserID.Text.Trim, txtPassword.Text)

Display record in datagridview after adding to database

I am able to add my records into my database without any problem, but I have trouble displaying it automatically into my datagridview.
In order for me to view my records in my datagridview, I need to close and restart the whole thing for it to appear. Is there any code that I've missed?
Private Sub btnAddEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddEmp.Click
Dim tranEmployee As SqlClient.SqlTransaction
sAdapter = New SqlDataAdapter(cmdEmployee)
Dim strID As String
Dim strName As String
Dim strPosition As String
Dim strContactNo As String
Dim strAddress As String
Dim strDOB As String
Dim strGender As String
Dim strSQL As String
conn.Open()
strID = mskEmployeeID.Text
strName = txtEmpName.Text
strPosition = cboEmpPosition.Text
strContactNo = mskEmpDOB.Text
strDOB = mskEmpDOB.Text
strAddress = txtEmpAddress.Text
If radEmpMale.Checked Then
strGender = "Male"
Else
strGender = "Female"
End If
strSQL = "INSERT INTO Users(userID,userName,userPosition,userGender,userDOB,userAddress)" & _
"VALUES(#ID,#NAME,#POSITION,#GENDER,#DOB,#ADDRESS)"
tranEmployee = conn.BeginTransaction()
With cmdEmployee
.Transaction = tranEmployee
.CommandText = strSQL
.Parameters.AddWithValue("#ID", strID)
.Parameters.AddWithValue("#NAME", strName)
.Parameters.AddWithValue("#POSITION", strPosition)
.Parameters.AddWithValue("#GENDER", strGender)
.Parameters.AddWithValue("#DOB", strDOB)
.Parameters.AddWithValue("#ADDRESS", strAddress)
.Connection = conn
End With
Try
cmdEmployee.ExecuteNonQuery()
tranEmployee.Commit()
Catch ex As Exception
tranEmployee.Rollback()
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
The code you've shown will successfully add a record to the database, but it doesn't make any attempt to refresh anything in the UI. Where is the code which binds the grid to records in the database? That code needs to be run again after this code runs.
I'm assuming that code exists in some sort of initializer for the form. Perhaps some sort of load event? You'll want to move that grid-binding code into its own function and call it from both the load event and at the end of this click event, probably right after the line where you commit the transaction.
You need to call your select statement subroutine again. The statement where you pulled your information from the database.
Try
cmdEmployee.ExecuteNonQuery()
tranEmployee.Commit()
Catch ex As Exception
tranEmployee.Rollback()
MessageBox.Show(ex.Message)
Finally
conn.Close()
selectUsers()
End Try