A NullReferenceException is thrown [duplicate] - vb.net

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
Using vb.NET I am trying to pull data from a database via a dataset but when running the code for the button, I get this error:
"An unhandled exception of type 'System.NullReferenceException' occurred in Full Program.exe
Additional information: Object reference not set to an instance of an object."
Here is my code, what is wrong with it?
Public Class mod_data
Dim inc As Integer
Dim con As OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Private Sub mod_data_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.ACE.12.0;"
dbSource = "\\fin01\JBU Visual Basic ICT\Ben\Full Program\Full Program\Component_Database.accdb;"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tblComponent_List"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Component_List")
con.Close()
MaxRows = ds.Tables("Component_List").Rows.Count
inc = -1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
txtComponent_ID.Text = ds.Tables("Component_List").Rows(1).Item(0)
txtComponent_Name.Text = ds.Tables("Component_List").Rows(1).Item(1)
'(...)
End Sub
'(...)
End Sub
#Crono
It is still throwing up the same error. This is the new code:
Still not working. This is the new code:
Public Class mod_data
Dim inc As Integer
Dim con As OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Private Sub mod_data_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet("Component_DatabaseDataSet3")
con = New OleDb.OleDbConnection("\\fin01\JBU Visual Basic ICT\Ben\Full Program\Full Program\Component_Database.accdb")
dbProvider = "PROVIDER=Microsoft.ACE.12.0;"
dbSource = "\\fin01\JBU Visual Basic ICT\Ben\Full Program\Full Program\Component_Database.accdb;"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tblComponent_List"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Component_List")
con.Close()
MaxRows = ds.Tables("Component_List").Rows.Count
inc = -1
End Sub
Private Sub NavigateRecords()
txtComponent_ID.Text = ds.Tables("Component_List").Rows(inc).Item(0)
txtComponent_Name.Text = ds.Tables("Component_List").Rows(inc).Item(1)
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
NavigateRecords()
Else
MsgBox("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
ElseIf inc = -1 Then
MsgBox("No Records Yet")
ElseIf inc = 0 Then
MsgBox("First Record")
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
NavigateRecords()
End If
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
NavigateRecords()
End If
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
ds.Tables("Component_List").Rows(inc).Item(0) = txtComponent_ID.Text
ds.Tables("Component_List").Rows(inc).Item(1) = txtComponent_Name.Text
MsgBox("Data updated")
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Component_List").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
da.Update(ds, "Component_List")
NavigateRecords()
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
txtComponent_ID.Text = ds.Tables("Component_List").Rows(1).Item(0)
txtComponent_Name.Text = ds.Tables("Component_List").Rows(1).Item(1)
End Sub
End Class

Your con connection object has not been instantiated. Put this line in before trying to set the connection string:
con = New OleDb.OleDbConnection()
You are going to have the same problem for ds. It should be instantiated before calling the adapter's Fill method.
ds = New DataSet()
As an additional advice, I'd suggest you remove the second parameter passed to the adapter's Fill method and fetch the DataTable instance this way:
MaxRows = ds.Tables(0).Rows.Count
And finally, next time, use the debugger to solve this kind of problem. It will be much easier and faster than asking on SO. ;)

You do not seem to have initialised 'con', thus it will contain null.
Initialise it before using it.
con = New OleDbConnection()

Related

Visual Basic Add Row Function Not Working After Reset Function

I will clarify my question. Here is background:
Creating a Database in Visual Studio 2019 using Visual Basic
Database consists of a list of Devices and Serial Numbers etc. that I must have account of
I have search functions, filtering functions, and a few editing functions
The problem I am encountering is that once I click the reset button (supposed to reset the dataviewgrid unsaved changes back to last saved changes) the add row function no longer works. The code throws no error but simply refuses to add a new row when clicking the button (Before hitting the reset button the add row button works fine)
Here is how I populate my database using sql:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As New SqlConnection("Connection String Placeholder")
Dim Table As New DataTable()
Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)
Adapter.Fill(Table)
DataGridView1.DataSource = Table
bind_data()
nextId = Convert.ToInt32(dt.Rows(dt.Rows.Count - 1)(0)) + 1
End Sub
I am also attempting to order my first column numerically and therefore I have the NextID value there as well and in my add row function (which may be the culprit)
Here is the add row and then reset function:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dr As DataRow = dt.NewRow()
dr(0) = nextId
dt.Rows.Add(dr)
nextId += 1
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim connection As New SqlConnection("Connection String Placeholder")
Dim Table As New DataTable()
Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)
Adapter.Fill(Table)
DataGridView1.DataSource = Table
nextId = Convert.ToInt32(dt.Rows(dt.Rows.Count - 1)(0)) + 1
End Sub
If any further questions please let me know, and thank you
Edit: Here is my bind_data() Sub
Private Sub bind_data()
connection.Open()
Dim cmdTxt As String = "SELECT * FROM TrackMain$"
da = New SqlDataAdapter(New SqlCommand(cmdTxt, connection))
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(da)
da.Fill(dt)
Dim source As BindingSource = New BindingSource With {
.DataSource = dt
}
DataGridView1.DataSource = source
End Sub
Here's the whole code of my test, and the code works for me.
Private dt As DataTable = New DataTable
Private da As SqlDataAdapter
Private connection As SqlConnection = New SqlConnection("connection string")
Dim nextId As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
bind_data()
nextId = Convert.ToInt32(dt.Rows(dt.Rows.Count - 1)(0)) + 1
End Sub
' Update database by DataGridView.'
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = DataGridView1.Rows.Count - 1 To 0
Dim row As DataGridViewRow = DataGridView1.Rows(i)
If Not row.IsNewRow AndAlso row.Cells(0).Value Is Nothing Then
DataGridView1.Rows.RemoveAt(i)
End If
Next
DataGridView1.EndEdit()
da.Update(dt)
End Sub
' Add new Row.'
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim dr As DataRow = dt.NewRow()
dr(0) = nextId
dt.Rows.Add(nextId)
nextId += 1
End Sub
' Reset the dt and DataGridView.'
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim Table As New DataTable()
dt.Clear()
Dim Adapter As New SqlDataAdapter("SELECT * FROM TrueTrack", connection)
Adapter.Fill(dt)
DataGridView1.DataSource = dt
nextId = Convert.ToInt32(dt.Rows(dt.Rows.Count - 1)(0)) + 1
End Sub
Private Sub bind_data()
connection.Open()
Dim cmdTxt As String = "SELECT * FROM TrueTrack"
da = New SqlDataAdapter(New SqlCommand(cmdTxt, connection))
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(da)
da.Fill(dt)
Dim source As BindingSource = New BindingSource With {
.DataSource = dt
}
DataGridView1.DataSource = source
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
connection.Close()
End Sub
Edit:
DataBase design(cancel auto-Increment of 'Id' ):
You can refer to the following code to sort the DataGridView by 'Id'.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Me.DataGridView1.Sort(Me.DataGridView1.Columns("Id"), ListSortDirection.Ascending)
End Sub
Then change the code to remove the DataGridView row.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If DataGridView1.Rows.Count > DataGridView1.CurrentCell.RowIndex + 1 Then
DataGridView1.Rows.RemoveAt(DataGridView1.CurrentCell.RowIndex)
End If
nextId = Convert.ToInt32(DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(0).Value) + 1
End Sub

Splitting data from database to 3 comboboxes

Hello there I wanted to ask if could you split to split data from my database and populate three textboxes. I have a column in my database called DOB (date of birth) its a Varchar I wanted to populate three combo boxes with the data from that column.The code is in the navigaterecord subprocedure. This is my code :
Imports System.Data.SQLite
Public Class Form1
Dim inc As Integer
Dim MaxRows As Integer
Dim ConnectionString As String = "Data Source=dbRoomBookings.db"
Dim ds As New DataSet
Dim dt As New DataTable
Dim mSQL As String = "SELECT * FROM Customer"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customer")
dt = ds.Tables(0)
MaxRows = ds.Tables("customer").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customer;"
dgvSearchResults.DataSource = display(msSQL, "customer")
MaxRows = ds.Tables("customer").Rows.Count
inc = -1
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Sub navigaterecords()
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(3) Then
cboYear.Text = ds.Tables("customer").Rows(inc).Item(3)
txtDbo.Text = ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(3)
End Sub
Private Sub BtnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Private Sub BtnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
navigaterecords()
End If
End Sub
Private Sub BtnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
navigaterecords()
Else
End If
End Sub

show patients that had a certain type of diagnose

I have a patient database. In that database i have a table "diagnosetypes" and a table with dossiers with a patient that received a certain diagnose.
In my diagnose form i have a list of diagnoses and now i want to add a listbox with a filter on all patients/dossiers that had this certain diagnose when that diagnose is selected in the combobox.
this is my current code
Public Class Diagnoses
Private Sub Diagnoses_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Tbl_DossiersTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Dossiers)
Me.Tbl_DiagnosesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Diagnoses)
Dim dt = Tbl_DiagnosesBindingSource
cboxDiagnose.DataSource = dt
cboxDiagnose.DisplayMember = "Diag_Type"
txtDiagnoseBeschrijving.Text = dt(0)("Diag_Type").ToString
cboxDiagnose.Focus()
End Sub
Private Sub CboxDiagnose_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cboxDiagnose.SelectionChangeCommitted
txtDiagnoseBeschrijving.Text = DirectCast(cboxDiagnose.SelectedItem, DataRowView)("Diag_Beschrijving").ToString
End Sub
Private Sub CboxDiagnose_Click(sender As Object, e As EventArgs) Handles cboxDiagnose.Click
RefreshData()
End Sub
Private Sub BtnAddDiagnose_Click(sender As Object, e As EventArgs) Handles btnAddDiagnose.Click
FormMakeDiagnoseType.Show()
End Sub
Private Sub RefreshData()
Try
Me.Tbl_DiagnosesBindingSource.Filter = Nothing
Me.Tbl_DiagnosesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Diagnoses)
Catch ex As Exception
MsgBox("Refresh Data Error: " & ex.Message.ToString(),
MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Add New Record Failed!")
End Try
End Sub
End Class
edit: I changed my code to look like this as a way of trying to accomplish it myself , but i won't work.
Private Sub Diagnoses_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\GoogleDrive\EINDWERK VBNET\PatientenDatabase.accdb")
cn.Open()
Dim cmmd As New OleDb.OleDbCommand("SELECT * FROM tbl_Dossiers WHERE OZ_ID.value = cboxDiagnose.text", cn)
Dim dr As OleDb.OleDbDataReader
dr = cmmd.ExecuteReader
Do While dr.Read
lboxPat_Diagcombo.Items.Add(dr("Rel_naam"))
Loop
cn.Close()
found something that works!
defined a binding source in code
then linked the listbox datasource to the binding source
then added following code :
Private Sub Onderzoeken_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Tbl_DossiersTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Dossiers)
Me.Tbl_OnderzoeksTypesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_OnderzoeksTypes)
Dim dt = Tbl_OnderzoeksTypesBindingSource
cboxOnderzoek.DataSource = dt
cboxOnderzoek.DisplayMember = "OZ_TypeOnderzoek"
cboxOnderzoek.ValueMember = "OZ_ID"
rtbBeschrijvingOnderzoek.Text = dt(0)("OZ_TypeOnderzoek").ToString
cboxOnderzoek.Focus()
Private Sub CboxDiagnose_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cboxOnderzoek.SelectionChangeCommitted
rtbBeschrijvingOnderzoek.Text = DirectCast(cboxOnderzoek.SelectedItem, DataRowView)("OZ_Onderzoeksbeschrijving").ToString
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\GoogleDrive\EINDWERK VBNET\PatientenDatabase.accdb")
cn.Open()
Dim ssql As String = "Select Rel_ID, tbl_Relaties.Rel_Naam &' ' & Rel_Voornaam as totaleNaam " &
"From tbl_Relaties INNER Join (tbl_Dossiers INNER Join tbl_DossRelatie On " &
"tbl_Dossiers.Dos_ID = tbl_DossRelatie.DR_DossID) ON tbl_Relaties.Rel_ID = tbl_DossRelatie.DR_RelID WHERE OZ_ID = " & cboxOnderzoek.SelectedValue
Dim cmmd As New OleDb.OleDbCommand(ssql, cn)
Dim dr As OleDb.OleDbDataReader
dr = cmmd.ExecuteReader
If dr.HasRows Then
Application.DoEvents()
bs_Relaties.DataSource = dr
lboxOZpatientcombo.DisplayMember = "totaleNaam"
lboxOZpatientcombo.ValueMember = "Rel_ID"
End If
cn.Close()
End Sub
since i added a binding source, the rest was easier to do:
Private Sub lboxOZpatientcombo_DoubleClick(sender As Object, e As EventArgs) Handles lboxOZpatientcombo.DoubleClick
Try
Dim MPF As New MainPatientform
MPF.display(Me, bs_Relaties.Current("rel_id"))
Catch ex As Exception
End Try
End Sub
thanks to all for new insights in this matter.

Syntax Error when Updating Database in Visual Studios

I connected my access database to my web form in Visual Studios but when try update records in the database it comes up with a Syntax Error.
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source= StudentDatabase.mdb"
sql = "SELECT * FROM StudentDatabase"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "StudentDatabase")
Label1.Text = ds.Tables("StudentDatabase").Rows(1).Item("Student First Name")
con.Open()
con.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("StudentDatabase").Rows(1).Item("Student First Name") = TextBox1.Text
da.Update(ds, "StudentDatabase")
End Sub
End Class
It should update the database with what was written in the text box but it comes up with a syntax error.

Index Out Of Range Exception In VB.NET

When I run the following code, after the ColourAddition(selectedstyle,styleselection.getIndex)="Y" line, I get an error every time and when I run the code without the aforementioned line, the program is a success. Please help me figure it out
Public Class Form1
Dim dbcon As New OleDb.OleDbConnection
Dim DR As OleDb.OleDbDataReader
Dim dr1 As OleDb.OleDbDataReader
Dim com As New OleDb.OleDbCommand
Dim com1 As New OleDb.OleDbCommand
Dim ChkdItm As Integer
Dim NoOfStyles As Integer
Dim NoOfColours As Integer
Dim SelectedStyle As Integer
Dim temp As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbcon.ConnectionString = "Provider= Microsoft.Ace.OLEDB.12.0; Data Source= CheckedListBox.accdb"
dbcon.Open()
com.CommandText = "Select * from ColourTable"
com1.CommandText = "Select * from StyleTable"
com1.Connection = dbcon
com.Connection = dbcon
DR = com.ExecuteReader
dr1 = com1.ExecuteReader
While dr1.Read
NoOfStyles += 1
End While
While DR.Read
ColoursClb.Items.Add(DR.GetString(1))
NoOfColours += 1
End While
SelectedStyle = StyleSelection.getIndex
End Sub
Public colourAddition(NoOfStyles, NoOfColours) As String
Private Sub AddColourBtn_Click(sender As Object, e As EventArgs) Handles AddColourBtn.Click
If ColoursClb.CheckedItems.Count > 0 Then
For Each ChkdItm In ColoursClb.CheckedIndices
colourAddition(SelectedStyle, StyleSelection.getIndex) = "Y"
Next
End If
End Sub
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
StyleSelection.Show()
End Sub
End Class
The error is showing on the line where "Next" is written