system.invalidoperationexception: Fill: selectCommand.Connection property has not been initialized - visual-studio

I'm working on connecting the MS Access database in Visual basic. Unfortunately, I cannot link the records from my data base into visual basic.
My database is located at C:\Users\lenovo\Desktop\GUI references\WindowsApplication1\WindowsApplication1\bin\Debug
Database name is smsenabler.mdb
Table to be connected is ProfessorListTable
The table contains fields of
ID | LastName | FirstName | MI | Department | Year Employed
My codes on my form are shown below:
Imports System.Data.OleDb
Public Class ProfessorList
Dim con As OleDbConnection
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
End Sub
Private Sub ProfessorList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim con As OleDbConnection = New OleDbConnection
con.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = ..\smsenabler.mdb"
con.Open()
showRecords()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Public Sub showRecords()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter("Select * from ProfessorListTable", con)
da.Fill(dt)
Dim myRow As DataRow
For Each myRow In dt.Rows
ListView1.Items.Add(myRow.Item(0))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myRow.Item(1))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myRow.Item(2))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myRow.Item(3))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myRow.Item(4))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myRow.Item(5))
Next
End Sub
ERROR MESSAGE
system.invalidoperationexception: Fill: selectCommand.Connection property has not been initialized. At System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter,IDbCommand command String method) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables,Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) at THESIS_GUI.ProfessorList.ProfessorList_Load(Object sender, EventArgs e) in C:\Users\lenovo\Desktop\GUI references\WindowsApplication1\WindowsApplication1\ProfessorList.vb:line17
LINE 17
showRecords()
It gives me an output with no records at all.It only shows a GUI with a field written on it. Thank you ..

One suggestion is to make sure your connection ('con') is available for all subroutines. I have used global variables before to prevent the need for opening and closing the connection (which would lead to problems in the old days). We both do a similar approach, but here is some code I have stripped bare (removed error traps, debug aids, etc.):
Global cnLocalData As ADODB.Connection
Public Sub Get_Connection()
Set cnLocalData = New ADODB.Connection
With cnLocalData
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Properties("Data Source") = "C:\data\SomeDB.mdb"
.Open
End With
End Sub

you are disconnected to the server, you must open you connection in the showRecords method.
This error error appear when you want to execute a command with the closed connection.

Related

Could not find installable ISAM while opening excel file with OLE driver

I am getting a "Could not find installable ISAM" error in the asp.net webform using visual basic. I am using .Net 4.6 framework. I tried different combinations of connection strings and I also tried with a single quote on Extended Properties as many online solutions suggested but the error did not go away. My code is as below:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim conn As OleDbConnection
Dim dta As OleDbDataAdapter
Dim dts As DataSet
Dim excel As String
excel = "C:\Users\ishfaq.babar\Downloads\aaa.xlsx"
'Dim openfiledialog As New OpenFileDialog
'conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties='Excel 12.0;'";")
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ishfaq.babar\Downloads\aaa.xlsx;Extended Properties='Excel 12.0;HDR=YES;Persist Security Info=False'")
dta = New OleDbDataAdapter("select * from [Sheet1$]", conn)
dts = New DataSet
dta.Fill(dts, "[Sheet1$]")
ExcelGridData.DataSource = dta
ExcelGridData.DataBind()
End Sub
i got error on line
dta.Fill(dts, "[Sheet1$]")
Moreover,I have installed both versions of ole drivers x64 and X86 and I had installed ole driver by command line as:
accessdatabaseengine /quiet
accessdatabaseengine_X64 /quiet
Because I was getting error from GUI Installer as:
microsoft.ace.oledb.12.0' provider is not registered on the local machine
ScreenShot of installed drivers is as follows:
OLE Drivers.Installed Access database Engine versions
ERROR has been resolved automatically with no change in code at all. Just after login again to my account after taking a break it runs successfully:
EDIT:
I Put conn.Open() after connection string.
New Code is As Below:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim conn As OleDbConnection
Try
Dim dta As OleDbDataAdapter
Dim dts As DataSet
Dim excel As String
excel = "C:\Users\ishfaq.babar\Downloads\aaa.xlsx"
'Dim openfiledialog As New OpenFileDialog
'conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties='Excel 12.0;'";")
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ishfaq.babar\Downloads\aaa.xlsx;Extended Properties='Excel 12.0;HDR=YES;Persist Security Info=False'")
conn.Open()
'PrintLine('ok')
' conn.Close()
dta = New OleDbDataAdapter("select * from [Sheet1$]", conn)
dts = New DataSet
dta.Fill(dts, "[Sheet1$]")
ExcelGridData.DataSource = dta
ExcelGridData.DataBind()
Catch ex As Exception
conn.Close()
End Try
End Sub
Read data successfully from excel file as below screenshot:
Result of data read from excel file

Datarowcollection cannot be converted to string In visual basic

I am working on a system right now in which When I put some value in my first text box (For eg. A primary key), I want the other textboxes to fetch the related data from my database and automatically get filled with it. I'm working on visual basic. I am new to this. For some Reason, it keeps on telling me that datarowcollection cannot be converted to string. Please help me get his working.
Here is the code:-
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim Cn As New SqlClient.SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\admin\Documents\Asset_Manager.mdf';Integrated Security=True;Connect Timeout=30")
Dim StrCmd As String = "Select * from Asset_Master where Asset_Id= '" & txt_allocate_asset_id.Text & "' "
Dim Command As SqlCommand
Dim da As SqlDataAdapter
Dim dt As New DataTable
Try
Cn.Open()
Command = New SqlCommand(StrCmd, Cn)
da = New SqlDataAdapter(Command)
Command.ExecuteNonQuery()
da.Fill(dt)
txt_demo_model_no.Text = dt.Rows[0][model_no].ToString()//The error line
Catch ex As Exception
Throw ex
End Try
End Sub

How to retrieve an image from an Access Database in Visual Studio?

I'm trying to retrieve an image stored in an Access Database to a Picturebox.
I'm not very fluent with this language, but my current code is as follows:
Private Sub lstUsers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstUsers.SelectedIndexChanged
Dim dt As New DataTable
dt = runSQL("Select * from tblUser where UserName = '" & lstUsers.SelectedItem.ToString & "'")
txtForename.Text = dt.Rows(0)(2)
txtSurname.Text = dt.Rows(0)(3)
txtCode.Text = dt.Rows(0)(6)
txtFinish.Text = dt.Rows(0)(7)
Dim data As Byte() = DirectCast(dt.Rows(0)(8), Byte())
Using ms As New MemoryStream(data)
Me.PictureBox1.Image = Image.FromStream(ms)
End Using
End Sub
When I try to run it and I select a username I get the following error message pointing to Image.FromStream(ms):
Parameter is not valid.
Any help would be appreciated.

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll

Whenever I run my program I get this error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
Sub admininfoo()
Dim q As String = "Select * from Table2 where AdminPassword=" & AdminLogin.TextBox1.Text
Dim cmd As New OleDb.OleDbCommand(q, connection)
Dim reader As OleDb.OleDbDataReader = cmd.ExecuteReader()
reader.Read()
AdminInterface.Label2.Text = reader("Name")
reader.Close()
End Sub
btw I am using Visual Basic 2013 and Microsoft Access Database
You are not sanitizing your inputs. If your password has an '?' character in it, the OleDb provider will interpret it as a parameter that you will need pass in, which you should be doing anyways, to prevent any injection.
Use the OleDbCommand.Parameters.AddWithValue method to add your parameter.
Dim q As String = "Select * from Table2 where AdminPassword=?"
Dim cmd As New OleDb.OleDbCommand(q, connection)
cmd.Parameters.AddWithValue("AdminPassword", AdminLogin.TextBox1.Text)
Dim reader As OleDb.OleDbDataReader = cmd.ExecuteReader()

VB dataset issue

The idea was to create a message box that stores my user name, message, and post datetime into the database as messages are sent.
Soon came to realize, what if the user changed his name?
So I decided to use the user id (icn) to identify the message poster instead. However, my chunk of codes keep giving me the same error. Says that there are no rows in the dataset ds2.
I've tried my Query on my SQL and it works perfectly so I really really need help to spot the error in my chunk of codes here.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim name As String
Dim icn As String
Dim message As String
Dim time As String
Dim tags As String = ""
Dim strConn As System.Configuration.ConnectionStringSettings
strConn = ConfigurationManager.ConnectionStrings("ufadb")
Dim conn As SqlConnection = New SqlConnection(strConn.ToString())
Dim cmd As New SqlCommand("Select * From Message", conn)
Dim daMessages As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim ds As New DataSet
cmd.Connection.Open()
daMessages.Fill(ds, "Messages")
cmd.Connection.Close()
If ds.Tables("Messages").Rows.Count > 0 Then
Dim n As Integer = ds.Tables("Messages").Rows.Count
Dim i As Integer
For i = 0 To n - 1
icn = ds.Tables("Messages").Rows(i).Item("icn")
Dim cmd2 As New SqlCommand("SELECT name FROM Member inner join Message ON Member.icn = Message.icn WHERE message.icn = #icn", conn)
cmd2.Parameters.AddWithValue("#icn", icn)
Dim daName As SqlDataAdapter = New SqlDataAdapter(cmd2)
Dim ds2 As New DataSet
cmd2.Connection.Open()
daName.Fill(ds2, "PosterName")
cmd2.Connection.Close()
name = ds2.Tables("PosterName").Rows(0).Item("name")
message = ds.Tables("Messages").Rows(i).Item("message")
time = ds.Tables("Messages").Rows(i).Item("timePosted")
tags = time + vbCrLf + name + ": " + vbCrLf + message + vbCrLf + tags
Next
txtBoard.Text = tags
Else
txtBoard.Text = "nothing to display"
End If
End Sub
Would it be more efficient to combine both cmd and cmd2, such that cmd becomes
SELECT msg.*,mem.Name FROM Message msg INNER JOIN Member mem ON msg.icn = mem.icn ?
This way, your Member.name would be in the same dataset as your Messages table, making your code much cleaner.
-Joel

Resources