The ConnectionString property has not been initialized error with VB.NET - vb.net

I am trying to fill a datagrid with data from access, but every time I run this program i get an error saying ConnectionString property has not been initialized i have tried everything i know. Can someone please help
Private Sub RefreshData()
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\My_db.accdb"
If Not cnn.State = ConnectionState.Open Then
' open connection '
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter()
Dim dt As New DataTable
'fill datatable'
da.Fill(dt)
Me.DataGridView1.DataSource = dt
' close connection'
cnn.Close()
End Sub
Private Sub BindGrid()
If Not cnn.State = ConnectionState.Open Then
' open connection '
cnn.Open()
End If
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = cnn
cmd.CommandText = "SELECT * FROM Training log WHERE Runner Name='" & Profile.UsernameTextBox.Text & "'"
cmd.ExecuteNonQuery()
Me.RefreshData()
cnn.Close()
End Sub

It looks like the OleDbCommand is never set to use the OleDbConnection object, and the DataAdapter is never set to use the command. Try this, which also fixes several other items that do not conform to commonly accepted practice:
'Put this module in a separate file
'Any and *ALL* code that talks directly to the DB should go in this module, and use the style of the RefreshData() method below.
Public Module DataLayer
Private Property ConnectionString() As String
Get
Return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\My_db.accdb"
End Get
End Property
'I left the name alone so you could match it up to your original code,
' but a better name would be something like "TrainingLogByRunner()"
Public Function RefreshData(ByVal RunnerName As String) As DataTable
Dim dt As New DataTable
Using cnn As New OleDb.OleDbConnection(ConnectionString), _
cmd As New OleDb.OleDbCommand("SELECT * FROM [Training log] WHERE [Runner Name]= ?", cnn), _
da As new OleDb.OleDbDataAdapter(cmd)
'**NEVER** use string concatentation to substitute this kind of value into a query!
'Had to guess at column type/length here
cmd.Parameters.Add("?", OleDbType.VarWChar, 40).Value = RunnerName
'No need to call Open() for the connection...
' the DataAdapter.Fill() method will manage opening/closing the connection
da.Fill(dt)
End Using
Return dt
End Function
End Module
Private Sub BindGrid()
Me.DataGridView1.DataSource = DataLayer.RefreshData(Profile.UsernameTextBox.Text)
End Sub

Related

i am currently getting this error, System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'

Imports System.Data
Imports System.Data.OleDb
Imports System.Data.DataTable
Public Class Form1
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Katlego\Documents\LoginDb.accdb")
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1, conn")
cmd.Parameters.Add("#username1", oleDbType:=OleDbType.VarChar).Value = txtusername.Text
cmd.Parameters.Add("#password1", oleDbType:=OleDbType.VarChar).Value = txtpassword.Text
Dim adapter1 As New OleDbDataAdapter(cmd)
Using logintable As New DataTable
Dim unused = adapter1.Fill(logintable)
If logintable.Rows.Count <= 0 Then
MsgBox("error username or password")
Else
MsgBox("login sucessfull")
End If
End Using
End Sub
You need to open the connection first
conn.Open()
There's a typo when you are initializing cmd object. You include the conn object inside the connection string. So the cmd object is missing a connection object.
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1, conn")
Should be:
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1", conn)
It is usually a good idea to separate you user interface code (where you click buttons and show message boxes) from your database code.
Connections, Commands and DataAdapters need to be disposed so they can release their unmanaged resources. Using...End Using blocks will do this for us.
Since you only want to know if the record exits you can just get the count. You had a typo in your command text. The closing quote included the conn.
We don't need DataTable or DataAdapter. That single piece of data only requires an ExecuteScalar which returns an Object so we need the CInt.
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If IsLoginValid(txtusername.Text, txtpassword.Text) Then
MsgBox("login sucessfull")
Else
MsgBox("error username or password")
End If
End Sub
Private Function IsLoginValid(uname As String, pword As String) As Boolean
Dim count As Integer
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Katlego\Documents\LoginDb.accdb"),
cmd As New OleDbCommand("select Count(*) from logintable where username1=#username1 and password1=#password1;", conn)
cmd.Parameters.Add("#username1", OleDbType.VarChar).Value = uname
cmd.Parameters.Add("#password1", OleDbType.VarChar).Value = pword
conn.Open()
count = CInt(cmd.ExecuteScalar)
End Using
If count = 1 Then
Return True
End If
Return False
End Function
There is still a big problem with the code. Passwords should NEVER be stored as plain text. They need to be salted and hashed but that is beyond the scope of this question.

How to fill a ComboBox using records from an Access database

I want to retrieve the data and display in a ComboBox but it's showing blank.
This is my code:
Imports System.Data.OleDb
Public Class frmAirwaybill
Private Sub frmAirwaybill_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim cm As OleDbCommand = New OleDbCommand("select acc_no from tblshipper order by acc_no")
cm.Connection = DBconnection()
Dim dr As OleDbDataReader = cm.ExecuteReader
Do While (dr.Read())
txtAccountNo.Items.Add(dr.Item("acc_no"))
Loop
dr.Close()
DBconnection.Close()
End Sub
End Class*
txtAccountNo is the ComboBox
What I want, when the form loads, is to load the accno from my database. How do I do that?
This is a screenshot showing the ComboBox with blank values:
My database connection is OK.
This is my connection on module file
Public Function DBconnection() As OleDbConnection
Dim con As New OleDb.OleDbConnection
Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"
con = New OleDb.OleDbConnection(constring)
con.Open()
Return con
End Function
The first thing to note is that you haven't opened the connection. This is probably the root cause.
That said, you are better binding to the .DataSource of the ComboBox using a DataTable and setting the .DisplayMember and .ValueMember properties.
I would also consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
Lastly, consider giving your ComboBox a better prefix. txt is often used for TextBox controls. I use cmb whilst others may use cbx. So in this case cmbAccountNo seems a better fit.
With the changes you code would look something like this:
Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"),
cmd As New OleDbCommand("SELECT [acc_no] FROM [tblshipper] ORDER BY [acc_no]", con)
con.Open()
dt.Load(cmd.ExecuteReader())
End Using
cmbAccountNo.DataSource = dt
cmbAccountNo.DisplayMember = "acc_no"
cmbAccountNo.ValueMember = "acc_no"

Multithreading Safe Calls not populating comboboxes vb.net

just curious on what im doing wrong here, the principle should work. Can anyone give me a hand?
The Code runs fine, but seems to not add them into my comboboxes
normal thread start like so
t1 = New Thread(New ThreadStart(AddressOf GetNewClientData))
t1.Start()
data is not empty or null... :)
Function GetNewClientData()
Try
Dim con As New SqlConnection
Dim myConString As String = My.Settings.ConString
Dim objcommand As SqlCommand = New SqlCommand
With objcommand
.Connection = con
Dim cmdText As String = "SELECT distinct Applicant,Client,Market,Project from AAClient order by Client"
.CommandText = cmdText
End With
con.ConnectionString = myConString
con.Open()
Using readerObj As SqlClient.SqlDataReader = objcommand.ExecuteReader
'This will loop through all returned records
While readerObj.Read
addClientInvoke(readerObj("Client").ToString)
addApplicantInvoke(readerObj("Client").ToString)
addMarketInvoke(readerObj("Client").ToString)
addProjectInvoke(readerObj("Client").ToString)
End While
End Using
con.Close()
Catch ex As Exception
End Try
Return Nothing
End Function
Delegate Sub addApplicant(s As String)
Sub addApplicantInvoke(ByVal s As String)
If CreateNewSite.cbApplicant.InvokeRequired Then
Dim d As New addApplicant(AddressOf addApplicantInvoke)
CreateNewSite.cbApplicant.Invoke(d, New Object() {s})
Else
CreateNewSite.cbApplicant.Items.Add(s)
End If
End Sub
Delegate Sub addClient(s As String)
Sub addClientInvoke(ByVal s As String)
If CreateNewSite.cbClient.InvokeRequired Then
Dim d As New addClient(AddressOf addClientInvoke)
CreateNewSite.cbClient.Invoke(d, New Object() {s})
Else
CreateNewSite.cbClient.Items.Add(s)
End If
End Sub
Delegate Sub addMarket(s As String)
Sub addMarketInvoke(ByVal s As String)
If CreateNewSite.cbMarket.InvokeRequired Then
Dim d As New addMarket(AddressOf addMarketInvoke)
CreateNewSite.cbMarket.Invoke(d, New Object() {s})
Else
CreateNewSite.cbMarket.Items.Add(s)
End If
End Sub
Delegate Sub addProject(s As String)
Sub addProjectInvoke(ByVal s As String)
If CreateNewSite.cbProject.InvokeRequired Then
Dim d As New addProject(AddressOf addProjectInvoke)
CreateNewSite.cbProject.Invoke(d, New Object() {s})
Else
CreateNewSite.cbProject.Items.Add(s)
End If
End Sub
possibly how i'm calling the delegate??
any help is appreciated
**** thanks to #jods here is the working code with one of the invoke methods****
starting thread in another modul
t1 = New Thread(New ParameterizedThreadStart(AddressOf GetNewClientData))
t1.Start(Me)
Code within the Modul
Function GetNewClientData(ByVal oldForm As CreateNewSite)
Try
Dim con As New SqlConnection
Dim myConString As String = My.Settings.ConString
Dim objcommand As SqlCommand = New SqlCommand
With objcommand
.Connection = con
Dim cmdText As String = "SELECT distinct Applicant,Client,Market,Project from AAClient order by Client"
.CommandText = cmdText
End With
con.ConnectionString = myConString
con.Open()
Using readerObj As SqlClient.SqlDataReader = objcommand.ExecuteReader
'This will loop through all returned records
While readerObj.Read
addApplicantInvoke(readerObj("Applicant").ToString, oldForm)
addClientInvoke(readerObj("Client").ToString)
addMarketInvoke(readerObj("Market").ToString)
addProjectInvoke(readerObj("Project").ToString)
End While
End Using
con.Close()
Catch ex As Exception
MsgBox(ex)
End Try
Return Nothing
End Function
Delegate Sub addApplicant(s As String, oldform As CreateNewSite)
Sub addApplicantInvoke(ByVal s As String, ByVal oldform As CreateNewSite)
If oldform.InvokeRequired Then
Dim d As New addApplicant(AddressOf addApplicantInvoke)
oldform.cbApplicant.Invoke(d, New Object() {s, oldform})
Else
oldform.cbApplicant.Items.Add(s)
End If
End Sub
The problem is CreateNewSite.cbProject. CreateNewSite is not your form instance. It's a nifty :p VB.NET feature called the default form instance:
VB has a concept of "Default Form Instances". For every Form in the application's namespace, there will be a default instance created in the My namespace under the Forms property.
You need to pass the correct form instance (i.e. 'Me' / 'this') to your background thread.

Reading tables using OleDBConnection

First off, i'm new to VB and this is my first project using OleDBConnection.
ok, so i'm trying to the most simple thing using oleDbConnection (i assume). I just want to read data from a table in the Access DB and display that information to dropboxes (or anything) in my winForm.
Public Class QueManger
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbDataAdapter As OleDbDataAdapter
Dim ConnectString As String = "Provider = Microsoft.Jet.OLEDB.4.0;" & "Data Source = \\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb"
Dim dtMain As DataTable
Private Sub QueManger_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StatusName()
End Sub
Private Sub StatusName()
Dim taxconn As OleDbConnection
Try
taxconn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb")
Dim taxcmd As OleDbCommand = taxconn.CreateCommand
taxcmd.CommandText = "SELECT StatusName FROM Status ORDER BY StatusName"
Dim rdr2 As OleDbDataReader
If taxconn.State = ConnectionState.Closed Then
taxconn.Open()
End If
rdr2 = taxcmd.ExecuteReader
'boxStatus.Items.Add("All")
While rdr2.Read()
boxClient.Items.Add(rdr2.Item("StatusName"))
End While
Catch ex As Exception
Finally
taxconn.Close()
End Try
End Sub
The error comes when it tries to run the "taxconn.Open()" function.
The error says "The Microsoft Access database engine cannot open or write to the file '\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb'. It is already opened exclusively by another user, or you need permission to view and write its data."
any thoughts?
try to close the opened table first in access if you are editing them, and try to add "#" before the string to use your path.
then try to use this connection string;
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + yourDataBasePath + ";Persist Security Info=False;";

ExecuteReader CommandText property has not been properly initialized

First of all sorry if some of the code isn't right. I'm still new to using sql on vb.net
I have the following code:
Imports MySql.Data.MySqlClient
Imports System.Data.SqlClient
Public Class Form1
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
Dim objConn As MySqlConnection
Dim objDataset As New DataSet
Dim objDataAdapter As MySqlDataAdapter
Dim myCommand As MySqlCommand
Dim sqlConn As String
objConn = New MySqlConnection("server=localhost;userid=root;database=attendance_system")
myCommand = objConn.CreateCommand
objConn.Open()
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.Fill(objDataset, "profile")
MsgBox("The Connection is Now 'OPEN'")
objReader.Read()
TextBox1.Text = objReader("student_name")
objReader.Close()
objConn.Close()
End Sub
End Class
I am using MySQL connector via vb.net in phpmyadmin and have set a database with records.
The connection string is working, but my problem is when I try to click the button to load the data in the textbox, I keep getting:
The CommandText property has not been properly initialized."
The error is on this line:
"Dim objReader As MySqlDataReader = myCommand.ExecuteReader"
I've tried a lot of fixes that I've found on this site and the others as well.
This is the problem:
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
You're declared the SQL after you've tried executing the query (and even then you don't set it as the SQL for the command). How would you expect that to work? Additionally, sqlConn is a very strange name for a variable declaring the SQL - I'd expect it to be a connection.
It looks like you're trying to mix too very different ways of fetching data:
Reading directly from the reader
Filling a DataSet with a data adapter
You shouldn't be mixing them like that. Work out which you actually want to do, take out all the code related to the other style, and then make sure you're doing everything in a sensible order.
From MySqlCommand Class and the example given as
Public Sub ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT * FROM Test.Dept"
Dim myConnection As New MySqlConnection(myConnString)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine(myReader.GetInt32(0).ToString() + ", " _
+ myReader.GetString(1))
End While
Finally
' always call Close when done reading.
myReader.Close()
' always call Close when done with connection.
myConnection.Close()
End Try
End Sub
Your command object is missing the select statement.