NullReferenceException was Unhandled "Object reference not set to an instance of an object." - vb.net

I have a problem sending data to my access database.
I get this error
NullReferenceExeption was Unhandled - "Object reference not set to an instance of an object."on this part of my codemaxrows = ds.Tables("asdf").Rows.Count
What would that mean?
Here is my code :
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
ID = TextID.Text
FName = Textfname.Text
LName = Textlname.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
If TextID.Tag & "" = "" Then
cmd = New OleDbCommand("INSERT INTO asdf(ID,fname,lname) " & _
"VALUES(' " & TextID.Text & "', '" & Textfname.Text & "', '" & Textlname.Text & "')", con)
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE asdf" & _
"SET ID=" & TextID.Text & _
", fname='" & Textfname.Text & "'" & _
",lname ='" & Textlname.Text & "'" & _
", WHERE ID =" & TextID.Tag
End If
btnClear.PerformClick()
MessageBox.Show("Data successfully saved!")
maxrows = ds.Tables("asdf").Rows.Count ' <---- Exception occurs here
inc = 1
con.Close()
RefreshData()
End Sub

Put a break-point (F9 or click in the margin) on this line of code: maxrows = ds.Tables("asdf").Rows.Count and run it.
Take these steps:
Hover over ds or right-click and select Quick Watch and see if it
says null.
If it doesn't, highlight ds.Tables("asdf") and Quick Watch it and
see if it's null.
If not, then highlight ds.Tables("asdf").Rows and see if that's
null.
One of these has to be null if it's crashing there. If that's the case, then you didn't fill it correctly or there wasn't nothing to fill it with.

Related

No value given for one or more required parameters (access)

I have 2 datatable with these fields
*dataordner
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
*datalemari
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
Lemari Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
and now I am very confused why i'm wrong
What I have tried:
I've done with my codes but always error with that error "no value given for one more...."
I call 2 table with if else in combobox(storage)
These are my code sequences, i think that's all true with selected item in combobox
note:
storage = combobox
Private Sub storage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles storage.SelectedIndexChanged
If storage.SelectedIndex = 1 Then
groupordner.Visible = True
grouplemari.Visible = False
Else
If storage.SelectedIndex = 2 Then
groupordner.Visible = False
grouplemari.Visible = True
End If
End If
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem = "Ordner" Then
str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
End Sub
There might me some control's value that is null or Nothing, you can use Debugging with Breakpoints to check null values Or there might be Objects that are not initialized.
You can also try the code below :
Note : I will recommend you to use Parameterized Query instead
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem Is Nothing Then
MsgBox("Plese Select the item first", MsgBoxStyle.Exclamation)
Else
If conn.State <> ConnectionState.Open Then
conn.Open() '' Assuming conn is your OleDbConnection
End If
Dim cmd As OleDbCommand = conn.CreateCommand
Try
If storage.SelectedItem = "Ordner" Then
Str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
Str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
Finally
conn.Close()
End Try
End If
End Sub

object reference not set to an instance of the object Error when adding data into my database

I am having a problem when i am trying to put this data into my database
I'm using Vstudio 2013 and MS Access as my database
my problem is everytime i click add to add the data in my database this error always popping object reference not set to an instance of the object. even i declared the
Here's my Add button Code
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
cmd.Connection = cn
cmd.CommandText = "INSERT INTO gradess ( StudentNo,StudentName,StudentSection,SubjectNo1,SubjectNo2,SubjectNo3,SubjectNo4,SubjectNo5,SubjectNo6,SubjectNo7,SubjectNo8,TotalAverage) " & "Values('" & txtStudentNo.Text & "','" & lblName.Text & "','" & lblSection.Text & "','" & txtSubject1.Text & "','" & txtSubject2.Text & "','" & txtSubject3.Text & "','" & txtSubject4.Text & "','" & txtSubject5.Text & "','" & txtSubject6.Text & "','" & txtSubject7.Text & "','" & txtSubject8.Text & "','" & lblTotalAverage.Text & "')"
cmd.ExecuteNonQuery()
refreshlist()
disablebutton()
MsgBox("Successfully Added!!", vbInformation, "Successful")
clear()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
When you declare a variable like Dim cn As OleDb.OleDbConnection you are just telling the compiler what type it is not creating an object of that type.
When you use the New keyword OleDb.OleDbConnection is not just the name of a class (the data type) but it is an actual method. It is calling the constructor of the class which returns an instance of the object.
In C# you are required to put the parenthesis after like OleDb.OleDbConnection() which shows you are calling a method. You can add the parenthesis in vb.net but it is not required but I think it is a good reminder of the difference between setting a data type and creating an object.
Your declaration should be : Dim cn As New OleDb.OleDbConnection Dim cmd As New OleDb.OleDbCommand
– F0r3v3r-A-N00b 20 mins ago

Update Access database using Visual Studio 2015 - VB.net

I am trying to do a simple update to an Access 2016 database. I am using Visual Studio/VB.net. I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore). I have tried two different ways to do this...using the update table adapter, for example:
MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
AvailabilityTextBox.Text, EmailTextBox.Text)
Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
But this method gives me the error of Syntax Error in UPDATE statement. Again I have used this method elsewhere with no problems. Below I will post all the code for this form.
Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class editMediators
Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")
' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
Dim cmd As New OleDbCommand
connect() ' open our connection
Try
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
MsgBox("Data Has Been Saved !", vbInformation)
Catch ex As Exception
MsgBox("Error when saving data: " & ex.Message)
End Try
End Sub
Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
DateTimePicker1.Value = Today()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
NewData = True
alertMsgBox2()
End Sub
Private Sub alertMsgBox2()
Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
"No: Exits the mediator update window without saving," & vbNewLine &
"Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
Case MsgBoxResult.Yes
MediatorsListBindingSource.EndEdit()
updateMediator()
'intentionally commented out
'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
'AvailabilityTextBox.Text, EmailTextBox.Text)
' Me.Close()
Case MsgBoxResult.No
MediatorsListBindingSource.CancelEdit()
Me.Close()
End Select
End Sub
Private Sub updateMediator()
Dim saveInfo As String
If NewData Then
Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
If Message = vbNo Then
Exit Sub
End If
Try
'Update mediator information
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
Catch ex As Exception
End Try
Else
Exit Sub
End If
runAccessSQL(saveInfo)
End Sub
There is obviously something I am missing, though I am not sure it is missing from the code. I checked my database fields and set them to string/text fields just to see if I could get it working. At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements. I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since. I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.
I am rather lost on what else to try as this seems like it should work one way or another. Any ideas what to look at and/or try?? Hopefully I can be pointed in the right direction.
Thanks :)
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.
Try this instead:
(Edited)
saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
mediatorID = '" & MediatorIDTextBox.Text & "'"
Also be sure to handle the date correctly. I usually force formatting in yyyy/mmm/dd format.

VB.NET use variable in textbox name

OK, so I have a form called quote_guidelines and i would like to use a procedure to update my database with values entered into the quote_guidelines form. The values are the descriptions and costs of decorations, food/drink and entertainment. Each tab has been assigned one of these additional servies. I wanted to make a procedure which would update the database with these new values.
The problem was that the query would have to contain a different table and different textbox names. I tried to solve this by saving the names of the tables and textboxes in variables, which will then be passed into the procedure.
the table variable works fine in the sql statement however, the textbox names dont.
I tried this:
quote_guidelines.Controls(description_textbox).Text
But this doesnt work.
Here is my query:
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls("" & description_textbox & "").Text & "', cost= " & quote_guidelines.Controls("" & cost_textbox & "").Text & " WHERE " & additional & "ID='" & y & "'"
When I run the program, i get the following error "An unhandled exception of type 'System.NullReferenceException' occurred in EHCC_BookingSystem.exe
Additional information: Object reference not set to an instance of an object."
I just realised that it might be some other stupid mistake i've made so here's the whole procedure:
Sub UpdateAdditionals(textbox3 As System.Object, textbox4 As System.Object, textbox5 As System.Object, textbox6 As System.Object, textbox7 As System.Object, textbox8 As System.Object, ByRef additional As String, ByRef description_textbox As String, ByRef cost_textbox As String)
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "Server=localhost;userid=root;password=root;database=comp4"
Dim reader As MySqlDataReader
MsgBox(additional & description_textbox & cost_textbox)
Try
mysqlconn.Open()
Dim query As String
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls.Find(description_textbox, True).FirstOfDefault().Text & "', cost= " & quote_guidelines.Controls.Find(cost_textbox, True).FirstOfDefault().Text & " WHERE " & additional & "ID='" & y & "'"
MsgBox(query)
command = New MySqlCommand(query, mysqlconn)
reader = command.ExecuteReader()
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
Try this - Replaced Controls in Controls.Find (Note the `True parameter to search the controls children):
query = "UPDATE " & additional & " SET description='" & TryCast(quote_guidelines.Controls.Find(description_textbox, True)(0), TextBox).Text & "', cost= " & TryCast(quote_guidelines.Controls.Find(cost_textbox, True)(0).Text & " WHERE " & additional & "ID='" & y & "'"
Also note you could do .FirstOfDefault() to get the first control (don't forget to cast):
Controls.Find("nameofcontrol", True).FirstOfDefault()

VB.NET SQL Server Insert - ExecuteNonQuery: Connection property has not been initialized

In the form load event, I connect to the SQL Server database:
Private Sub AddBook_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myConnection = New SqlConnection("server=.\SQLEXPRESS;uid=sa;pwd=123;database=CIEDC")
myConnection.Open()
End Sub
Here in the Insert event, I use the following code:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")")
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
And It produces the following error:
ExecuteNonQuery: Connection property has not been initialized
Connection Assignment - You aren't setting the connection property of the SQLCommand. You can do this without adding a line of code. This is the cause of your error.
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")", MyConnection)
Connection Handling - You also need to remove `MyConnection.Open' from your Load Handler. Just open it and close it in your Click Handler, as you are currently doing. This is not causing the error.
Parameterized SQL - You need to utilize SQL Parameters, despite the fact that you are not using a Stored Procedure. This is not the cause of your error. As Conrad reminded me, your original code dumps values straight from the user into a SQL Statement. Malicious users will steal your data unless you use SQL Parameters.
Dim CMD As New SqlCommand("Select * from MyTable where BookID = #BookID")
CMD.Parameters.Add("#BookID", SqlDbType.Int).Value = CInt(TXT_BookdID.Text)
You need to set the Connection property on the command:
myCommand.Connection = myConnection
Pretty much what the error message implies - the Connection property of the SqlCommand object hasn't been assigned to the connection you opened (in this case you called it myConnection).
Also, a word of advice here. Do some reading on sql parameters - doing sql concatenation from user input without any sanity checks is the way SQL injection attacks happen.
This is one way to do it:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand( _
"INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, " & _
" EnterDate, CatID, RackID, Amount) " & _
"VALUES(#bookCode, #bookTitle, #author, #publishingYear, #price, #enterDate, " & _
" #catId, #rackId, #amount)")
myCommand.Connection = myConnection
with myCommand.Parameters
.AddWithValue("bookCode", txtBookCode.Text)
.AddWithValue("bookTitle", txtTitle.Text)
.AddWithValue("author", txtAuthor.Text)
.AddWithValue("publishingYear", txtPublishYear.Text)
.AddWithValue("price", txtPrice.Text)
.AddWithValue("enterDate", txtEnterDate.Text)
.AddWithValue("catId", txtCategory.Text)
.AddWithValue("rackId", txtRack.Text)
.AddWithValue("amount", txtAmount.Text)
end with
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
Module Module1
Public con As System.Data.SqlClient.SqlConnection
Public com As System.Data.SqlClient.SqlCommand
Public ds As System.Data.SqlClient.SqlDataReader
Dim sqlstr As String
Public Sub main()
con = New SqlConnection("Data Source=.....;Initial Catalog=.....;Integrated Security=True;")
con.Open()
frmopen.Show()
'sqlstr = "select * from name1"
'com = New SqlCommand(sqlstr, con)
Try
com.ExecuteNonQuery()
'MsgBox("success", MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message())
End Try
'con.Close()
'MsgBox("ok", MsgBoxStyle.Information, )
End Sub
End Module
Please try to wrap the use of your connections (including just opening) inside a USING block. Assuming the use of web.config for connection strings:
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("web.config_connectionstring").ConnectionString)
Dim query As New String = "select * from Table1"
Dim command as New SqlCommand(query, connection)
Using connection
connection.Open()
command.ExecuteNonQuery()
End Using
And PARAMETERIZE anything user-entered.. please!