VB - Value cannot be null error - sql

The problem I am having is as follows:
I am using an SQL query to take data out of a table like so:
Dim query As String = "SELECT Pronunciation, Character FROM [Hiragana List] WHERE Pronunciation='" & pronunciation & "';"
Dim instruction = New SqlCommand(query, sqlCon)
Dim da As New SqlDataAdapter
da.SelectCommand = instruction
da.Fill(HiraganaList)
This should then take the data from the table and fill-in a datatable called "Hiragana List", however when the code reaches the line
da.Fill(Hiragana List)
The operation of the program stops and it instead returns this error:
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Data.dll
Additional information: Value cannot be null.
I took a look at the "Hiragana List" table itself and changed it so that it would accept Nulls in each of the field in order to see if it would fix it, unfortunately it still returns the same error.
(edit) Here is the declaration for the datatable 'Hiragana List':
Dim connectionString As String = "Server=my_server;Database=name_of_db;User Id=user_name;Password=my_password"
Dim sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename='J:\Computing Coursework\real project\KES\KES\Kana List.mdf';Integrated Security=True;Connect Timeout=30")
Dim HiraganaList As DataTable
Dim KanjiList As DataTable
Dim Katakana As DataTable
Dim YoonList As DataTable
Dim YoonKataList As DataTable

Ok on your code befor da.Fill(HiraganaList) add this Code :
HiraganaList = New DataTable
you Need this to avoid null Exception.

Related

invalid column name RDLC Report Viewer says while populating data to data source using multiple data sources

I am trying to print an RDLC report that gets data from multiple data sources. The first data source is filled with data while the other data source gives the following error
"Invalid Column Name 'INV123'"
The code for filling the data sources is as follows:
frmInvoiceReport.DataTable_InvoiceTableAdapter.Fill(frmInvoiceReport.SIS_DBDataSet.DataTable_Invoice)
frmInvoiceReport.DataTable_InvoiceInfoTableAdapter1.Fill(frmInvoiceReport.SIS_DBDataSet.DataTable_InvoiceInfo)
'The DataSet created.
Dim myConnection As SqlConnection = New SqlConnection(cs)
Dim myDA As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM [View_Invoice_Details] Where InvID = " & txtID.Text, myConnection)
Dim myDS As New DataSet
myDA.Fill(myDS, "DataTable_Invoice")
Dim myDa2 As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM [View_InvoiceInfo] Where InvoiceNo = " & txtInvoiceNo.Text, myConnection)
Dim myDs2 As New DataSet
myDa2.Fill(myDs2, "DataTable_InvoiceInfo")
frmInvoiceReport.ReportViewer1.LocalReport.DataSources.Clear()
Dim DtSrc As ReportDataSource = New ReportDataSource("SIS_DBDataSet", myDS.Tables("DataTable_Invoice"))
Dim DtSrc2 As ReportDataSource = New ReportDataSource("SIS_DBDataSet", myDs2.Tables("DataTable_InvoiceInfo"))
frmInvoiceReport.ReportViewer1.LocalReport.DataSources.Add(DtSrc)
frmInvoiceReport.ReportViewer1.LocalReport.DataSources.Add(DtSrc2)
frmInvoiceReport.ReportViewer1.RefreshReport()
frmInvoiceReport.ShowDialog()
I am not sure where the error arises. I have debugged the code and it catches an exception saying that the column name is invalid. I need a quick fix for that.

vb.net Loading Images from Access Database to DataTable?

So I have a MS Access Database with 1 table (Records) and 2 fields in it ("RecordID" (Number), which is the primary key, and "LowRes" (OLE Object) which is a low Resolution image). There are about 100 records.
I/m trying to load the Access Table into a DataTable (ID_Table) in VB.net.
Code so far:
Dim cnString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=SBS2257_ID.accdb;"
Dim theQuery As String = "SELECT [RecordID], [LowRes] FROM [Records];"
Using CN As New OleDbConnection(cnString)
Dim command As New OleDbCommand(theQuery, CN)
Using objDataAdapter = New OleDbDataAdapter(command)
Dim ID_Table As New DataTable
CN.Open()
Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
Dim picture As Image = Nothing
Using stream As New IO.MemoryStream(pictureData)
picture = Image.FromStream(stream)
objDataAdapter.Fill(ID_Table)
End Using
End Using
End Using
However the "DirectCast" command fails when I tell it to look at more then 1 field in my SQL statement with a datatype mismatch (if I just do [LowRes] it does not throw a error). However, I get stuck again when trying to apply the result to the table via the objDataAdapter, it doesnt fill the table with anything? I also notice that "picture" only contains the first image in the database.
I could put this database query in a function using "WHERE RECORDID=..." and loop it manually building the table returning "picture" each time, but Id like to avoid running a function 100 times, esp one that access a database.
Is it possible to read the whole database that contains images and just load it directly into a Datatable in one big swoop?
EDIT: So I got this to work:
Dim strConnection As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=SBS2257_ID.accdb;"
Dim strSQL As String = "SELECT [RecordID], [LowRes] FROM [Records];"
Using objConnection = New OleDbConnection(strConnection)
Using objCommand = New OleDbCommand(strSQL, objConnection)
Using objDataAdapter = New OleDbDataAdapter(objCommand)
Dim objDataTable As New DataTable("IDs")
objDataAdapter.Fill(objDataTable)
Return objDataTable
End Using
End Using
End Using
how ever when I go to view row 0, col 1 which should be the first LowRes image via a .ToString Useing this code:
Private Sub PrintValues(ByVal table As DataTable)
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
MsgBox(row(col).ToString())
Next col
Next row
End Sub
It just displays "System.Byte[]". It knows its a Byte datatype, but how do I display that in a picturebox?
The ExecuteScalar() executes the query, and returns the first column of the first row in the result set returned by the query.
as your query is
Dim theQuery As String = "SELECT [RecordID], [LowRes] FROM [Records];"
the first column is RecordID which is not a Byte().
you can change your query as following:
Dim theQuery As String = "SELECT [LowRes] FROM [Records];"
or you have to use other methods to get data from the database
Dim strSql As String = "SELECT [RecordID], [LowRes] FROM [Records]"
Dim dtb As New DataTable
Using cnn As New OleDbConnection(connectionString)
cnn.Open()
Using dad As New OleDbDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using

Error Adding Data to Access Database

I am trying to add a new record to an Access database. I am new to Visual Basic but have been searching for an answer to this. Here is my code so far:
Dim ID As Integer = CInt(IDBox.Text)
Dim password As Integer = CInt(PasswordBox.Text)
Dim first As String = FirstName.Text
Dim last As String = LastName.Text
Dim access As Integer = CInt(AccessLevel.Text)
Dim conn As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Tristan\Documents\Visual Studio 2015\Projects\Keno\Keno\Users.accdb")
conn.Open()
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter("SELECT * FROM Users", conn)
da.Fill(ds, "Users")
Dim cb As New OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("ID") = ID
dsNewRow.Item("First_Name") = first
dsNewRow.Item("Last_Name") = last
dsNewRow.Item("Password") = password
dsNewRow.Item("Access_Level") = access
ds.Tables("Users").Rows.Add(dsNewRow)
cb.GetInsertCommand()
da.Update(ds, "Users")
conn.Close()
MsgBox("User added successfully!")
Running this gets an error:
An unhandled exception of type System.Data.OleDb.OleDbException
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
Any help is appreciated!
The issue is almost certainly the fact that "Password", which you have used as a column name, is a reserved word. Any identifiers used in SQL code that are reserved words or contain special characters, e.g. spaces, must be escaped. A command builder doesn't do that by default. You have to set the QuotePrefix and QuoteSuffix properties yourself to make it do so. For an Access database, you would use "[" and "]" as the property values respectively.

Adding SQL Parameter fails

This is a new concept for me and I can't quite see what's causing the error
I'm attempting to populate a datagridview control from a single field in an Access database (from a combo and Text box source).
Using literals works, but not with the parameter.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Backend & ";Persist Security Info=False;")
Dim command As New OleDbCommand("Select Year from tblTest ", conn)
Dim criteria As New List(Of String)
If Not cboYear.Text = String.Empty Then
criteria.Add("Year = #Year")
command.Parameters.AddWithValue("#Year", cboYear.Text)
End If
If criteria.Count > 0 Then
command.CommandText &= " WHERE " & String.Join(" AND ", criteria)
End If
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
Dim UserRet As New DataTable
UserQuery.Fill(UserRet)
With frmDGV.DataGridView2
.DataSource = UserRet
End With
frmDGV.DataGridView2.Visible = True
frmDGV.Show()
Trying to Fill the datatable shows exception 'No value given for one or more required parameters.'
The value of command.CommandText at that point is "Select Year from tblTest WHERE Year = #Year"
Your instance of OleDbDataAdapter was created using two parameters query text and connection.
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
In this case DataAdapter doesn't know about parameters at all.
Instead use constructor with paremeter of type OleDbCommand.
Dim UserQuery As New OleDbDataAdapter(command)
In your code instance of OleDbCommand already associated with connection

Query/Update MS Access Records

I am attempting to populate items into a datagrid and then update them back into the database using 2 buttons (one loads, one will save) and a datagrid on a form. I keep running into "Syntax error (missing operator) in query expression" upon update and I am not sure why. Another question i have is where do my DataAdapter and Dataset need to be dimensioned in memory? Under the class?
'this loads my data from db into datagrid
Dim con As New OleDb.OleDbConnection
Dim sql As String
con.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=dbsrc.mdb"
con.Open()
sql = "SELECT * from [Employee Assignments]"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Assignments")
con.Close()
DataGridView1.DataSource = ds.Tables("Assignments")
The following code should update my database to reflect changes made in the datagridview
'this will eventually update the datagrid back into the db
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim con As New OleDb.OleDbConnection
'Dim sql As String
con.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=dbsrc.mdb"
con.Open()
da.Update(ds, "Assignments")
con.Close()
DataGridView1.DataSource = ds.Tables("Assignments")
I read this artcle on msdn - http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update.aspx - but it did not seem to help much, I am confused but I believe my problem is not identifying and passing the correct dataset back into the database. How should I deal with the dataset that I pull, modify, and then send back into the DB using the DataAdapter?
When a table contains spaces in its name you should inform the CommandBuilder about this problem
setting the QuotePrefix and QuoteSuffix property to avoid errors
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
The default for these twos is an empty string and thus, when you try to write your changes back to the database, you get a syntax error.