Results 1 to 6 of 6

Thread: Help Object reference not set to an instance of an object.

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Feb 2010
    Posts
    22

    Help Object reference not set to an instance of an object.

    / using vb.net 2010
    /using m.s access database

    i already finish my program and the program works perfectly by using a single table in Microsoft Access. but when i tried to add a new table and set a value accordingly.

    error occured : Object reference not set to an instance of an object. NullReferenceException was unhandled.

    / form code

    dssNewRow = ds.Tables("tblstudentsecond").NewRow() - error................

    Code:
    Imports System.Data.OleDb
    
    Public Class Form1
    
        Dim inc As Integer
        Dim maxrows As Integer
        Dim picPath As String
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            get_student()
            connection()
    
            sql = "Select * From tblstudent"
            da = New OleDb.OleDbDataAdapter(sql, con)
    
            da.Fill(ds, "tblstudent")
    
            con.Close()
    
            maxrows = ds.Tables("tblstudent").Rows.Count
            inc = 0
    
    
    
        End Sub
    
        Private Sub NavigateRecords()
    
            On Error Resume Next
    
            txtid.Text = ds.Tables("tblstudent").Rows(inc).Item(0)
            txtlname.Text = ds.Tables("tblstudent").Rows(inc).Item(1)
            txtfname.Text = ds.Tables("tblstudent").Rows(inc).Item(2)
            txtmi.Text = ds.Tables("tblstudent").Rows(inc).Item(3)
            txtaddress.Text = ds.Tables("tblstudent").Rows(inc).Item(4)
    
            txtloanamount.Text = ds.Tables("tblstudentsecond").Rows(inc).Item(0)
            txtinterest.Text = ds.Tables("tblstudentsecond").Rows(inc).Item(1)
            txtyears.Text = ds.Tables("tblstudentsecond").Rows(inc).Item(2)
            txtmonthlypayment.Text = ds.Tables("tblstudentsecond").Rows(inc).Item(3)
    
    
            connection()
            sql = "SELECT * From tblstudent WHERE id ='" & txtid.Text & "'"
            cmd = New OleDbCommand(Sql, con)
            dr = cmd.ExecuteReader()
    
            If dr.Read Then
                picStudent.Image = Image.FromFile(Application.StartupPath & "\Images\" & dr("stud_pic"))
            End If
    
            con.Close()
    
    
        End Sub
    
        Private Sub btnnext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnnext.Click
            If inc <> maxrows - 1 Then
                inc = inc + 1
                NavigateRecords()
    
            Else
                MsgBox("No More Records found", MsgBoxStyle.Exclamation, "Next")
            End If
        End Sub
    
        Private Sub btnprev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnprev.Click
            If inc > 0 Then
                inc = inc - 1
    
                NavigateRecords()
            Else
                MsgBox("You hit the First Record", MsgBoxStyle.Exclamation, "Prev")
            End If
        End Sub
    
        Private Sub btnfirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnfirst.Click
            If inc <> 0 Then
                inc = 0
    
                NavigateRecords()
            End If
        End Sub
    
        Private Sub btnlast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlast.Click
            If inc <> maxrows - 1 Then
                inc = maxrows - 1
                NavigateRecords()
            End If
        End Sub
    
        Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
            Dim cb As New OleDb.OleDbCommandBuilder(da)
    
            '    Dim cb As SqlCommandBuilder
            '    cb = New SqlCommandBuilder(da)
    
            '  ds.Tables("tblstudent").Rows(inc).Item("ID") = txtid.Text
            ds.Tables("tblstudent").Rows(inc).Item("Lname") = txtlname.Text
            ds.Tables("tblstudent").Rows(inc).Item("Fname") = txtfname.Text
            ds.Tables("tblstudent").Rows(inc).Item("Mi") = txtmi.Text
            ds.Tables("tblstudent").Rows(inc).Item("Address") = txtaddress.Text
    
            dss.Tables("tblstudentsecond").Rows(inc).Item("LoanAmount") = txtloanamount.Text
            dss.Tables("tblstudentsecond").Rows(inc).Item("Interest") = txtinterest.Text
            dss.Tables("tblstudentsecond").Rows(inc).Item("Years") = txtyears.Text
            dss.Tables("tblstudentsecond").Rows(inc).Item("MonthlyPayment") = txtmonthlypayment.Text
    
            da.Update(ds, "tblstudent")
            da.Update(dss, "tblstudentsecond")
            MsgBox("Data updated")
        End Sub
    
        Private Sub btnaddnew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaddnew.Click
            btncommit.Enabled = True
            btnaddnew.Enabled = False
            btnupdate.Enabled = False
            btndelete.Enabled = False
    
            txtid.Clear()
            txtfname.Clear()
            txtlname.Clear()
            txtmi.Clear()
            txtaddress.Clear()
            txtloanamount.Clear()
            txtinterest.Clear()
            txtyears.Clear()
            txtmonthlypayment.Clear()
            txtid.Focus()
        End Sub
    
        Private Sub btncancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancel.Click
            btncommit.Enabled = False
            btnaddnew.Enabled = True
            btnupdate.Enabled = True
            btndelete.Enabled = True
    
            inc = 0
            NavigateRecords()
        End Sub
        Private Sub btncommit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncommit.Click
    
            If inc <> -1 Then
                Dim cb As New OleDb.OleDbCommandBuilder(da)
    
                Dim picfaculty As String
    
                Dim FileToCopy As String
                Dim NewCopy As String
    
                FileToCopy = picPath
                NewCopy = Application.StartupPath & "\Images\" & lblPicName.Text
    
                If System.IO.File.Exists(FileToCopy) = True Then
                    System.IO.File.Copy(FileToCopy, NewCopy)
                    picfaculty = lblPicName.Text
                Else
                    picfaculty = "pic.png"
                End If
    
                Dim dsNewRow, dssNewRow As DataRow
    
                dsNewRow = ds.Tables("tblstudent").NewRow()
                dssNewRow = ds.Tables("tblstudentsecond").NewRow()
    
    
                'ds.Tables("tblstudent").NewRow()
    
                dsNewRow.Item("ID") = txtid.Text
                dsNewRow.Item("Lname") = txtlname.Text
                dsNewRow.Item("Fname") = txtfname.Text
                dsNewRow.Item("Mi") = txtmi.Text
                dsNewRow.Item("Address") = txtaddress.Text
    
                dssNewRow.Item("LoanAmount") = txtloanamount.Text
                dssNewRow.Item("Interest") = txtinterest.Text
                dssNewRow.Item("Years") = txtyears.Text
                dssNewRow.Item("MonthlyPayment") = txtmonthlypayment.Text
    
                ds.Tables("tblstudent").Rows.Add(dsNewRow)
                ds.Tables("tblstudentsecond").Rows.Add(dsNewRow)
                da.Update(ds, "tblstudent")
                da.Update(dss, "tblstudentsecond")
    
                MsgBox("New Record added to the Database", MsgBoxStyle.Information, "Save")
    
                btncommit.Enabled = False
                btnaddnew.Enabled = True
                btnupdate.Enabled = True
                btndelete.Enabled = True
    
                get_student()
    
            End If
    
            ' da.Update(ds, "tblstudent")
        End Sub
    
        Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click
            Dim cb As New OleDb.OleDbCommandBuilder(da)
            '  Dim cb As SqlCommandBuilder
            ' cb = New SqlCommandBuilder(da)
    
            ds.Tables("tblstudent").Rows(inc).Delete()
            maxrows = maxrows - 1
            inc = 0
            NavigateRecords()
            da.Update(ds, "tblstudent")
        End Sub
    
        Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Dim dlg As OpenFileDialog = New OpenFileDialog()
            Dim res As DialogResult = dlg.ShowDialog()
    
            With dlg
                .Filter = "All Image File (*.jpg;*.bmp;*.gif;*.png)|*.jpg;*.bmp;*.gif;*.png"
                .Title = "All Image File"
            End With
    
            If res = Windows.Forms.DialogResult.OK Then
    
                Dim str As String()
                str = Split(dlg.FileName, "\")
    
                For Each c As String In str
                    If c.EndsWith(".jpg") Or c.EndsWith(".jpeg") Or c.EndsWith(".png") Or c.EndsWith(".gif") Or c.EndsWith(".bmp") Or c.EndsWith(".JPG") Or c.EndsWith(".JPEG") Or c.EndsWith(".PNG") Or c.EndsWith(".GIF") Or c.EndsWith(".BMP") Then
                        lblPicName.Text = c
                        picPath = dlg.FileName
                        picStudent.Image = Image.FromFile(picPath)
                    End If
                Next
            End If
    
        End Sub
    
        Private Sub get_student()
    
            Try
                lvstudent.Items.Clear()
                connection()
                sql = "SELECT * From tblstudent order by id asc"
                cmd = New OleDbCommand(sql, con)
                dr = cmd.ExecuteReader
    
                While dr.Read
                    Dim lv As ListViewItem = lvstudent.Items.Add(dr("id"))
    
                    With lv.SubItems
                        .Add(dr("Lname"))
                        .Add(dr("Fname"))
                        .Add(dr("Mi"))
                        .Add(dr("Address"))
                    End With
    
                End While
                con.Close()
    
            Catch ex As Exception
    
                'MessageBox.Show(ex.ToString())
            End Try
        End Sub
    
        Private Sub view_student()
    
            connection()
    
            listselect = lvstudent.SelectedItems.Item(0).Text
    
            sql = "SELECT * From tblstudent WHERE id ='" & listselect & "'"
            cmd = New OleDbCommand(sql, con)
            dr = cmd.ExecuteReader()
    
            If dr.Read Then
                txtid.Text = dr("ID")
                txtlname.Text = dr("Lname")
                txtfname.Text = dr("Fname")
                txtmi.Text = dr("Mi")
                txtaddress.Text = dr("Address")
                lblPicName.Text = dr("stud_pic")
    
                picStudent.Image = Image.FromFile(Application.StartupPath & "\Images\" & dr("stud_pic"))
    
            End If
            con.Close()
    
        End Sub
        Private Sub lvstudent_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvstudent.Click
            Call view_student()
        End Sub
    
    
    
        Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
            Me.Close()
    
        End Sub
    
        Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
            Dim search As String
    
            search = InputBox("Please input id to search..", "Search")
    
            lvstudent.Items.Clear()
            connection()
    
            sql = "SELECT * From tblstudent where id = '" & search & "'"
            cmd = New OleDbCommand(sql, con)
            dr = cmd.ExecuteReader
    
            While dr.Read
                Dim lv As ListViewItem = lvstudent.Items.Add(dr("id"))
    
                With lv.SubItems
                    .Add(dr("Lname"))
                    .Add(dr("Fname"))
                    .Add(dr("Mi"))
                    .Add(dr("Address"))
                End With
    
            End While
            con.Close()
    
        End Sub
    
    
        Private Sub btnrefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnrefresh.Click
            Call get_student()
        End Sub
    
        Private Sub btncalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncalculate.Click
            Dim loan_am, interest_ra, payment_1 As Double
            Dim num_years As Integer
    
            loan_am = CDbl(txtloanamount.Text.Trim)
            interest_ra = CDbl(txtinterest.Text.Trim)
            If interest_ra > 1 Then interest_ra = interest_ra / 100
    
            num_years = CInt(txtyears.Text.Trim)
    
            payment_1 = Pmt(interest_ra / 12, num_years * 12, -1 * loan_am)
    
            txtmonthlypayment.Text = Format(payment_1, "P#,##0.00")
        End Sub
    
    End Class
    /modconnection

    Code:
    Imports System.Data.OleDb
    
    Module modConnection
        Public sql, listselect As String
        Public ds, dss As New DataSet
        Public da As New OleDb.OleDbDataAdapter
        Public cmd As New OleDb.OleDbCommand
        Public dr As OleDb.OleDbDataReader
    
        Public con As New OleDb.OleDbConnection
        Public dbProvider As String
        Public dbSource As String
    
        Public Sub Connection()
    
            Try
                dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
                dbSource = "Data Source = D:\database\tblstudent.accdb"
                con.ConnectionString = dbProvider & dbSource
    
                con.Open()
            Catch ex As Exception
                MsgBox(Err.Description, MsgBoxStyle.Critical, "Database Path Error")
            End Try
    
        End Sub
    End Module
    if you want to see my program here's the file link :

    http://www.mediafire.com/#08pb7jtz807gl

  2. #2
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Help Object reference not set to an instance of an object.

    That error if very easy to solve. It happens when you try to access an object from a variable that is set to Nothing. My guess is that ds.Tables("tblstudentsecond") is returning Nothing hence there is nothing to call NewRow on. It could also mean that ds is Nothing. You have to check when the program breaks to see.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  3. #3
    Frenzied Member
    Join Date
    Oct 2012
    Location
    Tampa, FL
    Posts
    1,187

    Re: Help Object reference not set to an instance of an object.

    at the break point, does this have value?

    Code:
     ds.Tables("tblstudentsecond").NewRow()

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Feb 2010
    Posts
    22

    Re: Help Object reference not set to an instance of an object.

    Quote Originally Posted by jayinthe813 View Post
    at the break point, does this have value?

    Code:
     ds.Tables("tblstudentsecond").NewRow()
    i dont know...

    because my plan is to add to tables on my database in ms access

    but its my first time to code using two tables

    i only make single table.

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Help Object reference not set to an instance of an object.

    Put a break point and find out....Hover the mouse over the line while the program is suspended. It'll tell you ds's value.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  6. #6
    Frenzied Member
    Join Date
    Oct 2012
    Location
    Tampa, FL
    Posts
    1,187

    Re: Help Object reference not set to an instance of an object.

    as well, I dont think you need two datasets. You can fill one same dataset with two tables like an array, then refer to the dataset instance you are currently working with. ds.tables[0] or ds.tables[1]. Check this and see if it helps you at all:
    Rows accesses the DataRow collection. The Add method creates one more row; however, you need to pass an instance of DataRow as the parameter. This DataRow object must have the same structure (columns) that the table, for this reason, you use the same table to create a new DataRoq: ds.Tables[0].NewRow()
    What about ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());?
    @user1856304 Rows accesses the Rows collection. The Add method creates one more row; however, you need to pass an instance of DataRow as the parameter. This DataRow object must have the same structure (columns) that the table, for this reason, you use the same table to create a new row: ds.Tables[0].NewRow()
    http://stackoverflow.com/questions/1...es0-rows-count

    not too familiar with datasets yet to be honest but your problem may be that you are not passing the instance of datarow to be created and then that instance added. Try out the above.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width